Loop over list of pairs

Alexander Schmolck a.schmolck at gmx.net
Fri Jun 6 16:14:00 CEST 2003


sismex01 at hebmex.com writes:
> > def xgroup(iter,n=2):
> >     """
> >     >>> list(xgroup(range(9), 3))
> >     [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
> >     """
> >     last = []
> >     for elt in iter:
> >         last.append(elt)
> >         if len(last) == n: yield tuple(last); last = []
> >
> Since 'n' is known from the start you don't need to
> test against it, nor build a list piecemeal.  Something
> like this seems a bit more solid:
> 
> def xgroup(Iterable, group=2):
>    """Return a groupwise iterator for Iterable."""
>    Iterator = iter(Iterable)
>    Length = range(group)
>    while 1:
>       yield [ Iterator.next() for i in xrange(group) ]

Indeed, thanks. In addition, `iter` is also a somewhat poor choice of name.
Which I guess goes to show that cutting and pasting some code from somewhere
for a usenet should always prompt a second look at it to avoid embarrassment
:)

So I updated my version to this (which uses a precomputed xrange object for a
gain in efficiency, as you clearly intended, but didn't actually do).

def xgroup(it, n=2):
    assert n>1    # ensure it doesn't loop forever
    it = iter(it)
    perTuple = xrange(n)
    while 1:
        yield tuple([it.next() for i in perTuple])

'as




More information about the Python-list mailing list