Iterating over several lists at once

Gal Diskin gal.diskin at gmail.com
Wed Dec 13 09:57:01 EST 2006


Thanks, that's an improvment (your first way).
But I still wish I could find an even shorter (or more elegent) way of
doing it. (Well, I guess if I expect every wish I have to come true I
should at least wish for something more valuable.)

Thanks again,
Gal

On Dec 13, 3:58 pm, "Fredrik Lundh" <fred... at pythonware.com> wrote:
> "Gal Diskin" wrote:
> > 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 I need to do is go over all n-tuples where the first argument is
> > from the first list, the second from the second list, and so on...
>
> > I was wondering if one could write this more easily in some manner
> > using only 1 for loop.
> > What I mean is something like this:
>
> > for (x1,x2,x3) in (l1,l2,l3):
> >    print "do something with", x1, x2, x3how about
>
>     for x1, x2, x3 in func(l1, l2, l3):
>         print x1, x2, x3
>
> where func is defined as, say,
>
>     def func(l1, l2, l3):
>         return ((x1, x2, x3) for x1 in l1 for x2 in l2 for x3 in l3)
>
> or if you prefer
>
>     def helper(l1, l2, l3):
>         for x1 in l1:
>             for x2 in l2:
>                 for x3 in l3:
>                     yield x1, x2, x3
> 
> </F>




More information about the Python-list mailing list