打破Python中的嵌套(双)循环

pro*_*eek 38 python nested-loops

我使用以下方法来破坏Python中的双循环.

for word1 in buf1:
    find = False
    for word2 in buf2:
        ...
        if res == res1:
            print "BINGO " + word1 + ":" + word2
            find = True
    if find:
        break
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来打破双循环?

Joh*_*ooy 45

也许不是你所希望的,但通常你会希望有一个break设置后find,以True

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 
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用生成器表达式将其压缩for成单个循环

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

您也可以考虑使用 itertools.product

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

  • itertools.product() 是一个很好的方法。 (4认同)

Gua*_*ard 37

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 
Run Code Online (Sandbox Code Playgroud)

  • 实际上,Python对异常有一些不同的方法,这种用法是可以的. (10认同)
  • 真?我从来没有见过推荐用于任何事情的例外情况,除了特别的事情. (5认同)

mag*_*ius 10

大多数情况下,您可以使用多种方法来创建一个与双循环相同的循环.

在您的示例中,您可以使用itertools.product替换您的代码段

import itertools
for word1, word2 in itertools.product(buf1, buf2):
    if word1 == word2:
        print "BINGO " + word1 + ":" + word2
        break
Run Code Online (Sandbox Code Playgroud)

其他itertools函数也适用于其他模式.


dka*_*ins 7

重构使用函数,以便在找到"宾果游戏"时返回.

允许显式中断嵌套循环的提议已被拒绝:http: //www.python.org/dev/peps/pep-3136/

  • 这应该是 IMO 投票最高的答案。 (2认同)