views:

46

answers:

1

Current version:

def chop(ar,size):
    p=len(ar)/size
    for i in xrange(p):
        yield ar[(i*size):((i+1)*size)]

ar is type of list().

What i want is that chop() takes iterator and return iterator.

for i in chop(xrange(9),3):
    for j in i:
       print j,
    print

prints

0 1 2
3 4 5
6 7 8
+2  A: 

There's an implementation in the itertools documentation:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
David Zaslavsky
That's a really clever implementation. Guess that's why it's in the documentation. Though I think it's slightly too clever. It needs a comment explaining how izip and the multiple pointers to the same iterator interact.
Omnifarious
@Omnifarious: I find that to be true of a lot of the examples in the `itertools` documentation (i.e. too clever). But I think thinking through it is a good exercise for understanding how you can do interesting things with iterators efficiently.
David Zaslavsky
I did not came that far in doc :D Thanks
ralu
@Omnifarious, This answer appears many times over on SO already. I think it is idiomatic Python by now :)
gnibbler