How to continue in nested loops in Python

后端 未结 6 1772
执念已碎
执念已碎 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 # 
          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
      

提交回复
热议问题