How to continue in nested loops in Python

后端 未结 6 1770
执念已碎
执念已碎 2020-12-09 01:39

How can you continue the parent loop of say two nested loops in Python?

for a in b:
    for c in d:
        for e in f:
            if somecondi         


        
相关标签:
6条回答
  • 2020-12-09 01:45

    Here's a bunch of hacky ways to do it:

    1. Create a local function

      for a in b:
          def doWork():
              for c in d:
                  for e in f:
                      if somecondition:
                          return # <continue the for a in b loop?>
          doWork()
      

      A better option would be to move doWork somewhere else and pass its state as arguments.

    2. Use an exception

      class StopLookingForThings(Exception): pass
      
      for a in b:
          try:
              for c in d:
                  for e in f:
                      if somecondition:
                          raise StopLookingForThings()
          except StopLookingForThings:
              pass
      
    0 讨论(0)
  • 2020-12-09 01:45
    from itertools import product
    for a in b:
        for c, e in product(d, f):
            if somecondition:
                break
    
    0 讨论(0)
  • 2020-12-09 01:56
    1. Break from the inner loop (if there's nothing else after it)
    2. Put the outer loop's body in a function and return from the function
    3. Raise an exception and catch it at the outer level
    4. Set a flag, break from the inner loop and test it at an outer level.
    5. Refactor the code so you no longer have to do this.

    I would go with 5 every time.

    0 讨论(0)
  • 2020-12-09 01:56

    Looking at All the answers here its all different from how i do it\n Mission:continue to while loop if the if condition is true in nested loop

    chars = 'loop|ing'
    x,i=10,0
    while x>i:
        jump = False
        for a in chars:
          if(a = '|'): jump = True
        if(jump==True): continue
    
    0 讨论(0)
  • 2020-12-09 01:57

    You use break to break out of the inner loop and continue with the parent

    for a in b:
        for c in d:
            if somecondition:
                break # go back to parent loop
    
    0 讨论(0)
  • 2020-12-09 01:57

    use a boolean flag

    problem = False
    for a in b:
      for c in d:
        if problem:
          continue
        for e in f:
            if somecondition:
                problem = True
    
    0 讨论(0)
提交回复
热议问题