Iterating over several lists at once
at
at at tuko.nl
Wed Dec 13 13:57:42 EST 2006
Sorry for breaking into this thread, but I agree completely that any
unnecessary indentations should be avoided. For the same reason I advocate
that the following syntax should work:
for x in some_list if some_condition:
... code ...
in stead of
for x in some_list
if some_condition:
... code ...
All the best!
@
PS: maybe using 'sets' can help you out for a particular problem.
Gal Diskin wrote:
> Nothing seriously wrong, but it's not too elegent. Especially when the
> number of lists you want to iterate over gets bigger (especially
> because of the indentation in python). As you noticed (an phrased
> better than me), what I was wondering is if there is a way to iterate
> over the cartesian product, but without actually doing all n for loops
> but using a single "for" loop.
>
> Thanks for replying me.
>
>
> On Dec 13, 3:58 pm, Roberto Bonvallet <Roberto.Bonval... at cern.ch>
> wrote:
>> Gal Diskin wrote:
>> > Hi,
>> > I am writing a code that needs to iterate over 3 lists at the same
>> > time, i.e something like this:
>>
>> > for x1 in l1:
>> > for x2 in l2:
>> > for x3 in l3:
>> > print "do something with", x1, x2, x3What's wrong with this?
>>
>> [...]
>>
>> > I'd be very happy to receive ideas about how to do this in one loop and
>> > with minimal initialization (if at all required).def
>> > cartesian_product(l1, l2, l3):
>> for i in l1:
>> for j in l2:
>> for k in l3:
>> yield (i, j, k)
>>
>> for (i, j, k) in cartesian_product(l1, l2, l3):
>> print "do something with", i, j, k
>>
>> --
>> Roberto Bonvallet
More information about the Python-list
mailing list