开发者

Break the nested (double) loop in Python [duplicate]

This question already has answers here: How can I break out of multiple loops? 开发者_运维百科 (38 answers) Closed 6 years ago.

I use the following method to break the double loop in Python.

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

Is there a better way to break the double loop?


The recommended way in Python for breaking nested loops is... Exception

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 


Probably not what you are hoping for, but usually you would want to have a break after setting find to 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 

Another way is to use a generator expression to squash the for into a single loop

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

You may also consider using itertools.product

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


Refactor using functions so you can return when you find your "bingo".

The proposal to allow explicit breaking out of nested loops has been rejected: http://www.python.org/dev/peps/pep-3136/


Most times you can use a number of methods to make a single loop that does the same thing as a double loop.

In your example, you can use itertools.product to replace your code snippet with

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

The other itertools functions are good for other patterns too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜