Split A List Into Roughly Equal Sized Pieces
Split A List Into Roughly Equal Sized Pieces
Submitted by Corey Goldberg on Thu, 10/04/2008 - 15:10.The Python Cookbook has a recipe for splitting a list into roughly equal-sized pieces:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425397
In the comments, there are several alterate implementations. Sebastian Hempel has an interesting take on it using slicing for the calculation of the list lengths. It basically looks like this:
def split_seq(seq, num_pieces): start = 0 for i in xrange(num_pieces):
stop = start + len(seq[i::num_pieces]) yield seq[start:stop] start = stop
This version of the function distributes the remaindered items evenly over the first few splits.
Example Usage:
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for seq in split_seq(seq,
3): print seq 