getting n items at a time from a generator
Raymond Hettinger
python at rcn.com
Sat Dec 29 15:12:30 EST 2007
> > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>
> > def chop(iterable, length=2):
> > return izip(*(iter(iterable),) * length)
>
> However, chop ignores the remainder of the data in the example.
There is a recipe in the itertools docs which handles the odd-length
data at the end:
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)
Raymond
More information about the Python-list
mailing list