goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Thursday, April 10, 2008

Split A List Into Roughly Equal Sized Pieces

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
#    Comments [2] |
Thursday, April 10, 2008 9:53:29 AM (Eastern Standard Time, UTC-05:00)
Dictionaries/arrays in Python give me a headache. I finally figured out (not on my own) how to do Perl's hashes in Python.

%foodCount;
$foodCount = {groceryList}++;

A list counter using hashes in Perl. So how would you do this in Python?

Anonymous
Thursday, April 10, 2008 10:04:26 AM (Eastern Standard Time, UTC-05:00)
itertools is your friend ...

http://docs.python.org/lib/itertools-functions.html#l2h-1069
"""
This makes possible an idiom for clustering a data series into n-length groups using "izip(*[iter(s)]*n)". For data that doesn't fit n-length groups exactly, the last tuple can be pre-padded with fill values using "izip(*[chain(s, [None]*(n-1))]*n)".
"""

Eugene Letuchy
Comments are closed.