Neal Becker <ndbeck...@gmail.com> 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.
This is my best effort... not using itertools as my brain doesn't seem to work that way! class Grouper(object): def __init__(self, n, i): self.n = n self.i = iter(i) def __iter__(self): while True: out = tuple(self.i.next() for _ in xrange(self.n)) if not out: break yield out g = Grouper(5, xrange(20)) print list(g) g = Grouper(4, xrange(19)) print list(g) Which produces [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14), (15, 16, 17, 18, 19)] [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18)] -- Nick Craig-Wood <n...@craig-wood.com> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list