Break a list into roughly equal sized pieces.
| Python |
1 2 3 4 5 6 | def split_seq(seq, size):
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return newseq
|
Discussion
Inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044
This requires that you know the length of the list beforehand, of course, so you can't use it with an arbitrary sequence as is. It's simple, but it's easy to create fencepost errors when implementing it.
>>> split_seq(range(10), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]


Comments
Naming suggestion. The second parameter, "size", would be better named "numPieces", since split_seq([]..., x) always returns a list with x pieces.
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
All integer approach. Here is an all integer method that builds a list of ranges first, then splices the sequence.
alternate implementation using integers. This version uses integer math and distributes the remaindered items evenly over the first few splits.
again, an integer approach. def splitCeil(seq, m):
def splitFloor(seq, m):
Another approach using slicing for the calculation of the list lengths.
Sign in to comment