Jason wrote:
Hey everyone--

I'm pretty new to Python, & I need to do something that's incredibly
simple, but combing my Python Cookbook & googling hasn't helped me out
too much yet, and my brain is very, very tired & flaccid @ the
moment....

I have a list of objects, simply called "list".  I need to break it
into an array (list of lists) wherein each sublist is the length of
the variable "items_per_page".  So array[0] would go from array[0][0]
to array[0][items_per_page], then bump up to array[1][0] - array[1]
[items_per_page], until all the items in the original list were
accounted for.


If you need to pad the last item:

def chunk( seq, size, pad=None ):
    '''
    Slice a list into consecutive disjoint 'chunks' of
    length equal to size. The last chunk is padded if necessary.

    >>> list(chunk(range(1,10),3))
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> list(chunk(range(1,9),3))
    [[1, 2, 3], [4, 5, 6], [7, 8, None]]
    >>> list(chunk(range(1,8),3))
    [[1, 2, 3], [4, 5, 6], [7, None, None]]
    >>> list(chunk(range(1,10),1))
    [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
    >>> list(chunk(range(1,10),9))
    [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
    >>> for X in chunk([],3): print X
    >>>
    '''
    n = len(seq)
    mod = n % size
    for i in xrange(0, n-mod, size):
        yield seq[i:i+size]
    if mod:
        padding = [pad] * (size-mod)
        yield seq[-mod:] + padding

If you search the list archive, there is surely an example which will do the same for an arbitrary iterable (in general, you can't assume that `len(seq)` will work for an iterable that is not a list, set or tuple). But if you are just starting with Python, don't worry about this.


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to