scotfl.ca

February, 2008

array_chunk in Python

def chunk(seq, chunk_size): “”"Split a sequence into chunks.

    >>> chunk(range(10),2)
    [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

    The final chunk may have fewer than chunk_size elements.
    >>> chunk(range(10),3)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    """
    return [
        seq[offset:offset+chunk_size]
        for offset in xrange(0, len(seq), chunk_size)
    ]

Posted on 23 February 2008 in Uncategorized

2 Comments »