itertools question

Peter Otten __peter__ at web.de
Thu May 14 16:40:33 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.

Depending on what you want to do with items that don't make a complete N-
tuple:

>>> from itertools import *
>>> items = range(10)

>>> list(izip(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]

>>> list(izip_longest(*(iter(items),)*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

>>> list(takewhile(bool, imap(tuple, starmap(islice, repeat((iter(items), 
3))))))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]

Peter




More information about the Python-list mailing list