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.
Another way would be something like this, the idea here is to use grouper, but get rid of
None
. In this case we'll have all 'small_parts' formed from elements at the first part of the list, and 'larger_parts' from the later part of the list. Length of 'larger parts' is len(small_parts) + 1. We need to consider x as two different sub-parts.The way I have it set up returns a list of tuples:
Here is one that adds
None
to make the lists equal lengthRounding the linspace and using it as an index is an easier solution than what amit12690 proposes.
This is the raison d'être for
numpy.array_split
*:*credit to Zero Piraeus in room 6
You could also use:
Here's one that could work:
Testing: