generate tuples from sequence

Neil Cerutti horpner at yahoo.com
Wed Jan 17 09:24:31 EST 2007


On 2007-01-17, Will McGugan <will at willmcgugan.com> wrote:
> Hi,
>
> I'd like a generator that takes a sequence and yields tuples containing
> n items of the sqeuence, but ignoring the 'odd' items. For example
>
> take_group(range(9), 3) -> (0,1,2) (3,4,5) (6,7,8)
>
> This is what I came up with..
>
>     def take_group(gen, count):
>         i=iter(gen)
>         while True:
>             yield tuple([i.next() for _ in xrange(count)])
>
> Is this the most efficient solution?

This is starting to seem like an FAQ. ;)

The Python library contains a recipe for this in the itertools
recipes in the documentation (5.16.3).

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)

It's more general and cryptic than what you asked for, though.

-- 
Neil Cerutti
We're not afraid of challenges. It's like we always say: If you want to go out
in the rain, be prepared to get burned. --Brazillian soccer player



More information about the Python-list mailing list