Home > front end >  Skip outter loop if meet condition
Skip outter loop if meet condition

Time:08-21

Hello I have 3 loop as follow:

for i1 in loop1:
    for i2 in loop2:
        for i3 in loop3:
            do sth here

now I have a condition for loop1 that if the condition is met then execute loop1 if not we run loop2 and loop3 only.

I know that in standard way it is:

if condition==True:
    for i1 in loop1:
        for i2 in loop2:
            for i3 in loop3:
                do sth
else:
    for i2 in loop2:
        for i3 in loop3:
            do sth

However, I am looking for some way that is compact like:

for i1 in loop1 if condition==True then do otherwise skip go to next inner loop
    for i2 in loop2:
        for i3 in loop3:
            do sth

CodePudding user response:

A way I approach this is:

for i1 in loop1 if Condition else [0]:
    for i2 in loop2:
        for i3 in loop3:
            do sth

Of course, this assumes i1 is never read in either case. [Edit, made it more compact]

CodePudding user response:

Use list comprehension if you are dealing with lists. Example: newlist = [x if 5 > 3 else 0 for x in range(3)]

  • Related