itertools question

N

Neal Becker

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.
 
P

Peter Otten

Neal said:
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.

Depending on what you want to do with items that don't make a complete N-
tuple:
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
3))))))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]

Peter
 
P

pataphor

Neal said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,132
Latest member
AnneHarpur

Latest Threads

Top