Efficient way to divide a list into lists of n size
You'll want to do something that makes use of List.subList(int, int) views rather than copying each sublist. To do this really easily, use Guava's Lists.partition(List, int) method:
List<Foo> foos = ...
for (List<Foo> partition : Lists.partition(foos, n)) {
// do something with partition
}
Note that this, like many things, isn't very efficient with a List
that isn't RandomAccess
(such as a LinkedList
).
Splitting a list into N parts of approximately equal length
This code is broken due to rounding errors. Do not use it!!!
assert len(chunkIt([1,2,3], 10)) == 10 # fails
Here's one that could work:
def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
Testing:
>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
Split a python list into other sublists i.e smaller lists
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
Divide a list into fixed number of list in java
Edit: Please refer to this solution below for partitioning in N times,
Java 8
class SamplePartition
{
public static void main (String[] args) throws java.lang.Exception {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
final int N=4;
System.out.println(part(l,N));
}
private static <T> List<List<T>> Part(List<T> objs, final int N) {
return new ArrayList<>(IntStream.range(0, objs.size()).boxed().collect(
Collectors.groupingBy(e->e%N,Collectors.mapping(e->objs.get(e), Collectors.toList())
)).values());
}
}
Using Guava
`List<List<Integer>> partitionedLists = Lists.partition(intList, partition`);
Apache Commons Util
List<List<Integer>> partitionedLists = ListUtils.partition(largeList, partition);
How do I split a list into equally-sized chunks?
Here's a generator that yields evenly-sized chunks:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]
For Python 2, using xrange
instead of range
:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), n):
yield lst[i:i + n]
Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:
[lst[i:i + n] for i in range(0, len(lst), n)]
For Python 2:
[lst[i:i + n] for i in xrange(0, len(lst), n)]
Split a List into smaller lists of N size
public static List<List<float[]>> SplitList(List<float[]> locations, int nSize=30)
{
var list = new List<List<float[]>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}
Generic version:
public static IEnumerable<List<T>> SplitList<T>(List<T> locations, int nSize=30)
{
for (int i = 0; i < locations.Count; i += nSize)
{
yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i));
}
}
Divide a list into smaller lists
So, I hardly tried to make it in one line. Here is what I ended up with
import math
nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
N = 3
lists = [nb_classes[math.ceil(i): math.ceil(i + len(nb_classes) / N)] for i in (len(nb_classes) / N * j for j in range(N))]
print(lists) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]
But this may be a little bit complicated, you just need to ceil your indexes
Split list into smaller lists (split in half)
A = [1,2,3,4,5,6]
B = A[:len(A)//2]
C = A[len(A)//2:]
If you want a function:
def split_list(a_list):
half = len(a_list)//2
return a_list[:half], a_list[half:]
A = [1,2,3,4,5,6]
B, C = split_list(A)
Related Topics
Using Variables Outside of an If-Statement
Printing Message on Console Without Using Main() Method
How to Get the Array Class for a Given Class in Java
Create File with Given Size in Java
How to Round Time to the Nearest Quarter Hour in Java
Is There a Priorityqueue Implementation with Fixed Capacity and Custom Comparator
Why Is Files.Lines (And Similar Streams) Not Automatically Closed
Exception Noclassdeffounderror for Cacheprovider
Find Out What Jvm Eclipse Is Running On
Remove Duplicates from Arraylists
Concurrent Threads Adding to Arraylist at Same Time - What Happens
Understanding the etc/Gmt Time Zone
Dynamic Generic Typing in Java
Writing in the Beginning of a Text File Java
Removing All the Rows of Defaulttablemodel