如何在 Python 中的嵌套循环中继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14829640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to continue in nested loops in Python
提问by James
How can you continuethe parent loop of say two nested loops in Python?
你怎么能continue在 Python 中说两个嵌套循环的父循环?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
I know you can avoid this in the majority of cases but can it be done in Python?
我知道在大多数情况下您可以避免这种情况,但可以在 Python 中完成吗?
采纳答案by Duncan
- Break from the inner loop (if there's nothing else after it)
- Put the outer loop's body in a function and return from the function
- Raise an exception and catch it at the outer level
- Set a flag, break from the inner loop and test it at an outer level.
- Refactor the code so you no longer have to do this.
- 从内部循环中断(如果之后没有其他内容)
- 将外循环的主体放在一个函数中并从该函数返回
- 引发异常并在外层捕获它
- 设置一个标志,中断内部循环并在外部级别对其进行测试。
- 重构代码,这样您就不再需要这样做了。
I would go with 5 every time.
我每次都会带5个。
回答by Tony The Lion
You use breakto break out of the inner loop and continue with the parent
你break用来打破内部循环并继续使用父级
for a in b:
for c in d:
if somecondition:
break # go back to parent loop
回答by Eric
Here's a bunch of hacky ways to do it:
这里有一堆hacky的方法来做到这一点:
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.
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
创建本地函数
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()更好的选择是将 doWork 移到其他地方并将其状态作为参数传递。
使用异常
class StopLookingForThings(Exception): pass for a in b: try: for c in d: for e in f: if somecondition: raise StopLookingForThings() except StopLookingForThings: pass
回答by John La Rooy
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break
回答by Samourai
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

