簡體   English   中英

如何在 Python 中的嵌套循環中繼續

[英]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 中完成嗎?

  1. 從內部循環中斷(如果之后沒有其他內容)
  2. 將外循環的主體放在一個函數中並從該函數返回
  3. 引發異常並在外層捕獲它
  4. 設置一個標志,從內部循環中斷並在外部級別進行測試。
  5. 重構代碼,這樣您就不再需要這樣做了。

我每次都會帶5個。

這里有一堆hacky的方法來做到這一點:

  1. 創建本地函數

    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 移到其他地方並將其狀態作為參數傳遞。

  2. 使用異常

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM