Best pattern/idiom

Heiko Wundram heikowu at ceosg.de
Tue Aug 10 08:49:07 EDT 2004


Am Dienstag, 10. August 2004 06:39 schrieb Michele Simionato:
> >>> import itertools
> >>> def chop(it, n):
>
> ...     tup = (iter(it),)*n
> ...     return itertools.izip(*tup)
> ...
>
> >>> list(chop([1,2,3,4,5,6],3)) [(1, 2, 3), (4, 5, 6)]
> >>> list(chop([1,2,3,4,5,6],2)) [(1, 2), (3, 4), (5, 6)]
> >>> list(chop([1,2,3,4,5,6],1)) [(1,), (2,), (3,), (4,), (5,), (6,)]

Problem being:

>>> list(chop([1,2,3,4,5,6],4))
[(1, 2, 3, 4)]

If you actually want to get back everything from iterator, better do something 
like:

def ichop(it,n,rtype=list):
    it = iter(it)
    empty = False
    while not empty:
        retv = []
        while not empty and len(retv) < n:
            try:
                retv.append(it.next())
            except StopIteration:
                empty = True
        if retv:
            yield rtype(retv)

>>> list(ichop([1,2,3,4,5,6],3))
[[1, 2, 3], [4, 5, 6]]
>>> list(ichop([1,2,3,4,5,6],2))
[[1, 2], [3, 4], [5, 6]]
>>> list(ichop([1,2,3,4,5,6],1))
[[1], [2], [3], [4], [5], [6]]
>>> list(ichop([1,2,3,4,5,6],4,tuple))
[(1, 2, 3, 4), (5, 6)]
>>> list(ichop([1,2,3,4,5,6],4))
[[1, 2, 3, 4], [5, 6]]

Heiko.



More information about the Python-list mailing list