打破Python中的嵌套(双)循环 [英] Break the nested (double) loop in Python
本文介绍了打破Python中的嵌套(双)循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下方法打破Python中的双重循环.
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?
推荐答案
可能不是您想要的,但是通常在将find
设置为True
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
另一种方法是使用生成器表达式将for
压缩为单个循环
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
您也可以考虑使用itertools.product
from itertools import product
for word1, word2 in product(buf1, buf2):
...
if res == res1:
print "BINGO " + word1 + ":" + word2
break
这篇关于打破Python中的嵌套(双)循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文