itertools question

Nick Craig-Wood nick at craig-wood.com
Thu May 14 10:30:02 EDT 2009


Neal Becker <ndbecker2 at 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 <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list