iterator question

George Sakkis george.sakkis at gmail.com
Tue Sep 26 19:58:23 CEST 2006


Neil Cerutti wrote:

> 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)

That's not quite the same as the previous suggestions; if the last
tuple is shorter than n, it pads the last tuple with padvalue. The OP
didn't mention if he wants that or he'd rather have a shorter last
tuple.

George




More information about the Python-list mailing list