如何在Python中继续嵌套循环

80

在Python中,如何继续父循环,假设有两个嵌套的循环?

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

我知道在大多数情况下你可以避免这种情况,但是在Python中能做到吗?


2
有没有任何理由不仅使用 break - Jon Clements
使用 break 来退出内部循环 - 这将立即继续执行外部循环。 - TyrantWave
2
还有一个类似的问题:https://dev59.com/jnVC5IYBdhLWcg3wxEJ1 - esycat
3
我已经修复了这个示例以确实需要使用 continue。 - James
当嵌套循环时,你应该考虑使用这种技术:展平嵌套循环 - D.L
8个回答

73
  1. 如果内层循环后没有其他内容,则跳出该循环
  2. 将外层循环的主体放入函数中,并从函数返回
  3. 引发异常并在外部级别捕获它
  4. 设置标志,从内部循环中退出并在外部级别测试它。
  5. 重构代码,使之不再需要执行此操作。

每次我都会选择5。


2
PHP 比 Python 更胜一筹的一个案例是,它对于 breakcontinue 有级别选项 :) - jave.web
我认为使用#2是实现#5的标准方式,除非在上下文中存在完全不同的解决问题的方法。 - Karl Knechtel

27
这里有一些取巧的方法:

  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移动到其他地方,并将其状态作为参数传递。
使用异常。
class StopLookingForThings(Exception): pass

for a in b:
    try:
        for c in d:
            for e in f:
                if somecondition:
                    raise StopLookingForThings()
    except StopLookingForThings:
        pass

17
你可以使用break来跳出内部循环,并继续执行外部循环的代码。
for a in b:
    for c in d:
        if somecondition:
            break # go back to parent loop

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

3

使用布尔标志

problem = False
for a in b:
  for c in d:
    if problem:
      continue
    for e in f:
        if somecondition:
            problem = True

1

看到这里所有的答案都与我做法不同\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

0
#infinite wait till all items obtained
while True:
    time.sleep(0.5)
    for item in entries:
        if self.results.get(item,None) is None:
            print(f"waiting for {item} to be obtained")
            break #continue outer loop
    else:
        break
    #continue

我希望能有一个带标签的循环...


0
lista = ["hello1", "hello2" , "world"]

for index,word in enumerate(lista):
    found = False
    for i in range(1,3):
        if word == "hello"+str(i):
            found = True
            break
        print(index)
    if found == True:
        continue
    if word == "world":
        continue
    print(index)


    

现在打印的是:

>> 1
>> 2
>> 2

这意味着第一个单词(索引=0)首先出现(在 continue 语句之前没有任何东西可以被打印)。第二个单词(索引=1)出现在第二个位置(单词“hello1”得以打印,但其余的未能打印),第三个单词出现在第三个位置,这意味着在 for 循环到达第三个单词之前,“hello1”和“hello2”这两个单词已经被打印。

总之,这只是使用 found = False / True 布尔值和 break 语句。

希望对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接