Home >Backend Development >C++ >How to Correctly Split a List into Smaller Lists of a Custom Size (e.g., 30 or less)?
Split the list into smaller lists of custom size
When splitting a list into smaller lists of a specific size, it can be frustrating to encounter incorrect list splitting. Let's explore how to modify your function splitList
to ensure it is accurately split into lists of size 30 or less.
The problem with your original function is the loop calculation: for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i>=0; i--)
. Instead of iterating from the desired number of sublists to 0, you are looping from a higher value, resulting in incorrect splitting.
The updated function should be:
<code class="language-c#">public static List<List<float>> splitList(List<float> locations, int nSize = 30) { List<List<float>> list = new List<List<float>>(); int numLists = (int)(Math.Ceiling((decimal)(locations.Count / nSize))); for (int i = 0; i < numLists; i++) { List<float> subLocat = new List<float>(locations); // 创建locations的副本 if (subLocat.Count >= ((i * nSize) + nSize)) subLocat.RemoveRange(i * nSize, nSize); else subLocat.RemoveRange(i * nSize, subLocat.Count - (i * nSize)); Debug.Log("Index: " + i.ToString() + ", Size: " + subLocat.Count.ToString()); list.Add(subLocat); } return list; }</code>
In this updated version, the loop iterates from 0 to the desired number of sublists (numLists). This ensures that the function starts splitting at the appropriate location. In addition, the code uses List<float> subLocat = new List<float>(locations);
to create a copy of locations
, avoiding the problem of the original list being modified.
The above is the detailed content of How to Correctly Split a List into Smaller Lists of a Custom Size (e.g., 30 or less)?. For more information, please follow other related articles on the PHP Chinese website!