如何在Python中的嵌套循环中继续

问题描述 投票:41回答:5

你怎么能在Python中说两个嵌套循环的父循环continue

for a in b:
    for c in d:
        for e in f:
            if somecondition:
                <continue the for a in b loop?>

我知道你可以在大多数情况下避免这种情况但可以在Python中完成吗?

python
5个回答
39
投票
  1. 从内循环中断(如果之后没有别的东西)
  2. 将外循环的主体放在一个函数中并从函数返回
  3. 提出异常并在外层捕获它
  4. 设置一个标志,从内循环中断并在外层测试它。
  5. 重构代码,以便您不再需要这样做。

我每次都会去5。


17
投票

这里有一堆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

11
投票
from itertools import product
for a in b:
    for c, e in product(d, f):
        if somecondition:
            break

5
投票

你使用break打破内循环并继续父

for a in b:
    for c in d:
        if somecondition:
            break # go back to parent loop

0
投票

使用布尔标志

problem = False
for a in b:
  for c in d:
    if problem:
      continue
    for e in f:
        if somecondition:
            problem = True
© www.soinside.com 2019 - 2024. All rights reserved.