breaking out of outer loops

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 29 16:33:12 EST 2008


On Jan 29, 8:55 pm, pataphor <patap... at gmail.com> wrote:
> On Tue, 29 Jan 2008 11:51:04 -0800 (PST)
>
> noemailplease0... at gmail.com wrote:
> > Any elegant way of breaking out of the outer for loop than below, I
> > seem to have come across something, but it escapes me
>
> > for i in outerLoop:
> >    for j in innerLoop:
> >        if condition:
> >           break
> >    else:
> >        continue
> >     break
>
> Ha! Think outside the box to begin with ...
>
> P.
>
> def cross(args):
>     ans = [[]]
>     for arg in args:
>         ans = [x+[y] for x in ans for y in arg]
>     return ans    

While we're at it, a generator version:

def iproduct(head=None, *tail):
    if head is None:
        return ((),)
    else:
        return ((x,)+y for x in head for y in iproduct(*tail))

for a, b, c in iproduct('124', 'ab', 'AB'):
    print a, b, c

;-)

--
Arnaud




More information about the Python-list mailing list