Iterating through two lists

matt matt at automagic.org
Sun Jun 23 22:19:36 CEST 2002


Sounds like you want to use list comprehension :
http://www.python.org/doc/current/tut/node7.html#SECTION007140000000000000000

eg :

print [(x,y) for x in (1,2,3,4) for y in (10,15,3,22) if x*y > 25]

regards
Matt


Curtis Taylor wrote:
> 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?
> 
> Thanks,
> 
> Curtis





More information about the Python-list mailing list