itertools question

pataphor pataphor at gmail.com
Fri May 15 14:03:38 CEST 2009


Neal Becker wrote:

> Is there any canned iterator adaptor that will 
> 
> transform:
> in = [1,2,3....]
> 
> into:
> out = [(1,2,3,4), (5,6,7,8),...]
> 
> That is, each time next() is called, a tuple of the next N items is 
> returned.

Here's one that abuses a for loop:

from itertools import islice

def grouper(seq,n):
     it = iter(seq)
     for x in it:
         yield (x,) + tuple(islice(it,n-1))

def test():
     L = range(11)
     n = 3
     for x in grouper(L,n):
         print x

if __name__ == '__main__':
     test()

BTW what's up with the followup to gmane?

P.



More information about the Python-list mailing list