itertools question

Lie Ryan lie.1296 at gmail.com
Thu May 14 17:38:20 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.
> 
> 



An option, might be better since it handles infinite list correctly:

 >>> lst = [1, 4, 2, 5, 7, 3, 2, 5, 7, 3, 2, 6, 3, 2, 6, 8, 4, 2]
 >>> d = 4
 >>> for x in itertools.groupby(enumerate(lst), lambda x: x[0] // d):
...     print(list(x[1]))
...
[(0, 1), (1, 4), (2, 2), (3, 5)]
[(4, 7), (5, 3), (6, 2), (7, 5)]
[(8, 7), (9, 3), (10, 2), (11, 6)]
[(12, 3), (13, 2), (14, 6), (15, 8)]
[(16, 4), (17, 2)]
 >>> [list(x[1]) for x in itertools.groupby(enumerate(lst), lambda x: 
x[0] // d)]
[[(0, 1), (1, 4), (2, 2), (3, 5)], [(4, 7), (5, 3), (6, 2), (7, 5)], 
[(8, 7), (9, 3), (10, 2), (11, 6)], [(12, 3), (13, 2), (14, 6), (15, 
8)], [(16, 4), (17, 2)]]




More information about the Python-list mailing list