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

Jam*_*mes 46 python

你怎么能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

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

我每次都会去5.

  • 6.使用itertools :) (5认同)
  • @gnibbler,在一般情况下#6⊂#5但是对于这个特殊情况,我会+1你的答案 (2认同)
  • PHP 击败 Python 的案例之一,因为它确实有“break”和“continue”的级别选项:) (2认同)

Eri*_*ric 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()
    
    Run Code Online (Sandbox Code Playgroud)

    更好的选择是将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
    
    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)


Ton*_*ion 5

break可以打破内循环并继续使用父级

for a in b:
    for c in d:
        if somecondition:
            break # go back to parent loop
Run Code Online (Sandbox Code Playgroud)