0

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

If you have an iterator iter with values i0, i1, i2, ..., what's the most Pythonic way to get an iterator whose values are

[i0, i1, i2], [i3, i4, i5], ...

The above would be the output to a hypothetical groupby(iter, 3).

Community
  • 1
  • 1
user792036
  • 722
  • 8
  • 14
  • 1
    More specifically, [this answer](http://stackoverflow.com/a/312644/989121) which applies to arbitrary iterables. – georg Aug 22 '12 at 14:57

2 Answers2

2

The itertools module has a recipe for this called grouper. Here is the excerpt copied straight from itertools documentation.

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61
0

The best solution that I can find (requires itertools):

groupby = lambda s,n : izip(*[iter(s)]*n)

but it feels slightly hacky and is hard to read

user792036
  • 722
  • 8
  • 14
  • That does not solve the problem in a general way for inputs that are not a multiple of the block size. izip basically ignores the last, not full, block of items. – yacc143 Nov 06 '14 at 10:12