你怎么能continue
在Python中说两个嵌套循环的父循环?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
Run Code Online (Sandbox Code Playgroud)
我知道你可以在大多数情况下避免这种情况但可以在Python中完成吗?
Dun*_*can 41
我每次都会去5.
Eri*_*ric 17
这里有一堆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()
Run Code Online (Sandbox Code Playgroud)
更好的选择是将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
Run Code Online (Sandbox Code Playgroud)Joh*_*ooy 11
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break
Run Code Online (Sandbox Code Playgroud)
您break
可以打破内循环并继续使用父级
for a in b:
for c in d:
if somecondition:
break # go back to parent loop
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46228 次 |
最近记录: |