[英]How to continue in nested loops in Python
如何在 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
看看這里的所有答案,它與我的做法完全不同\\n 任務:如果嵌套循環中的 if 條件為真,則繼續執行 while 循環
chars = 'loop|ing'
x,i=10,0
while x>i:
jump = False
for a in chars:
if(a = '|'): jump = True
if(jump==True): continue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.