Loop over list of pairs

sismex01 at hebmex.com sismex01 at hebmex.com
Fri Jun 6 15:51:41 CEST 2003


> From: SISMEX01 
> Sent: Thursday, June 05, 2003 3:59 PM
> 
> > From: Alexander Schmolck [mailto:a.schmolck at gmx.net]
> > Sent: Thursday, June 05, 2003 3:58 PM
> > 
> > Thomas Güttler <guettler at thomas-guettler.de> writes:
> > 
> > > Hi!
> > > 
> > > What is the prefered way of loop over
> > > a list like this?
> > >  mylist=[1, "one", 2, "two", 3, "three"]
> > 
> > you could use this:
> > 
> > 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) ]
> 
> hth!
> 
> -gca
>

Yuck!  Sorry for replying to my own post, darn untested code.
Please remove "Length = ..." from the previous, as it's
superfluous.

-gca

--

Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list