你怎么能在Python中说两个嵌套循环的父循环continue
?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
我知道你可以在大多数情况下避免这种情况但可以在Python中完成吗?
我每次都会去5。
这里有一堆hacky方法:
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
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break
你使用break
打破内循环并继续父
for a in b:
for c in d:
if somecondition:
break # go back to parent loop
使用布尔标志
problem = False
for a in b:
for c in d:
if problem:
continue
for e in f:
if somecondition:
problem = True