在Python中打破嵌套(双重)循环

53 投票
4 回答
111917 浏览
提问于 2025-04-15 21:21

我在Python中使用以下方法来中断双重循环。

for word1 in buf1:
    find = False
    for word2 in buf2:
        ...
        if res == res1:
            print "BINGO " + word1 + ":" + word2
            find = True
    if find:
        break

有没有更好的方法来中断双重循环呢?

4 个回答

18

使用函数来重构代码,这样当你找到“宾果”时就可以直接返回。

关于允许在嵌套循环中明确退出的提议已经被拒绝了:http://www.python.org/dev/peps/pep-3136/

75

在Python中,打破嵌套循环的推荐方法是使用... 异常

class Found(Exception): pass
try:
    for i in range(100):
        for j in range(1000):
            for k in range(10000):
               if i + j + k == 777:
                  raise Found
except Found:
    print i, j, k 
64

这可能不是你想要的答案,但通常在把 find 设置为 True 后,你会想要加一个 break 来结束循环。

for word1 in buf1: 
    find = False 
    for word2 in buf2: 
        ... 
        if res == res1: 
            print "BINGO " + word1 + ":" + word2 
            find = True 
            break             # <-- break here too
    if find: 
        break 

另一种方法是使用生成器表达式,把 for 循环简化成一个单一的循环。

for word1, word2 in ((w1, w2) for w1 in buf1 for w2 in buf2):
    ... 
    if res == res1: 
        print "BINGO " + word1 + ":" + word2
        break 

你也可以考虑使用 itertools.product 这个工具。

from itertools import product
for word1, word2 in product(buf1, buf2):
    ... 
    if res == res1: 
        print "BINGO " + word1 + ":" + word2
        break 

撰写回答