Iterating through two lists

Andrae Muys amuys at shortech.com.au
Mon Jun 24 00:25:52 EDT 2002


Curtis Taylor <c.tee at verizon.net> wrote in message news:<c.tee-FF2C9D.10574923062002 at news.bellatlantic.net>...
> In article <7934d084.0206031700.377c691e at posting.google.com>,
>  amuys at shortech.com.au (Andrae Muys) wrote:
> 
> > "Denis S. Otkidach" <ods at fep.ru> wrote in message 
> > news:<mailman.1022234790.26965.python-list at python.org>...
> > > On Fri, 24 May 2002, jb wrote:
> > > 
> > > j> I have two lists, x and y with the property len(x) = len(y).
> > > j>
> > > j> I should like to achive this (x is a list of class instances)
> > > j>
> > > j>   for (a,b) in (x,y): a.f(b)
> > > j>
> > > j> Is there a fancy way of doing this or have I to introduce an
> > > j> auxillary
> > > j> counter (that is very easy but maybe not very "lispy", that
> > > j> is
> > > j> "python-like").
> > > 
> > > If lists are not very lange try this:
> > > 
> > > for a, b in zip(x, y): a.f(b)
> > 
> > If the lists are large then you probably need something along the lines of 
> > xzip.
> > 
> > def xzip(*args):
> >     iters = [iter(a) for a in args]
> >     while 1:
> >         yield tuple([i.next() for i in iters])
> > 
> > Andrae Muys
> 
> 
> Hi Andrae,
> 
> I've got a similar situation I'm dealing with, in that I have 2 lists of 
> dictionaries, each of which is of equal length. What's different 
> however, is that I need to do an equality check for the values of 2 of 
> the keys (both of which exist in each dictionary), then set the value of 
> the 2nd dictionary's key to the value of that of the first's, e.g.:
> 
> if dict2[key1] == dict1[key1]:
>    dict2[key2] = dict1[key2]
> 
> I'm concerned with overhead, as the 2 lists could potentially be very 
> large. Can your xzip function be extended to do such a thing?
> 

1. I don't understand where you're getting key1 or key2 from?  

2. xzip() is reasonably well defined semantically, so I doubt you
really want to extend it, rather I suggest you consider a custom
generator (or 2).

3. I suspect you should probably read the section on iterators and
generators in the What's New in Python 2.1 bulletin.

4. One useful thing to note is that you can always collapse a
generator/iterator into a tuple/list by using the tuple()/list()
builtin functions.

Andrae



More information about the Python-list mailing list