iterator question

Neil Cerutti horpner at yahoo.com
Tue Sep 26 13:46:21 EDT 2006


On 2006-09-26, Neal Becker <ndbecker2 at gmail.com> wrote:
> Any suggestions for transforming the sequence:
>
> [1, 2, 3, 4...]
> Where 1,2,3.. are it the ith item in an arbitrary sequence
>
> into a succession of tuples:
>
> [(1, 2), (3, 4)...]
>
> In other words, given a seq and an integer that specifies the
> size of tuple to return, then for example:

It turns out there's a itertools recipe to do this; the last one
in the itertools recipe book:

def grouper(n, iterable, padvalue=None):
    """
    grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')

    """
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

-- 
Neil Cerutti
There are two ways to argue with a woman, and neither of them
work. --Carlos Boozer



More information about the Python-list mailing list