What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.
I'm looking for something like even_split(L, n)
that breaks L
into n
parts.
def chunks(L, n):
""" Yield successive n-sized chunks from L.
"""
for i in xrange(0, len(L), n):
yield L[i:i+n]
The code above gives chunks of 3, rather than 3 chunks. I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.
Here is my solution:
Produces
See
more_itertools.divide
:Install via
> pip install more_itertools
.As long as you don't want anything silly like continuous chunks:
This will do the split by a single expression:
The list in this example has the size 18 and is divided into 5 parts. The size of the parts differs in no more than one element.
Here's another variant that spreads the "remaining" elements evenly among all the chunks, one at a time until there are none left. In this implementation, the larger chunks occur at the beginning the process.
For example, generate 4 chunks from a list of 14 elements:
Have a look at numpy.split: