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, x3

What'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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to