打破 Python 中的嵌套(双)循环
我使用以下方法来打破Python中的双循环。
for word1 in buf1:
find = False
for word2 in buf2:
...
if res == res1:
print "BINGO " + word1 + ":" + word2
find = True
if find:
break
有没有更好的方法来打破双循环?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 中打破嵌套循环的推荐方法是... Exception
The recommended way in Python for breaking nested loops is... Exception
可能不是您所希望的,但通常您希望在将
find
设置为True
后进行break
另一种方法是使用生成器表达式将
for
压缩为单个循环您也可以考虑使用
itertools.product
Probably not what you are hoping for, but usually you would want to have a
break
after settingfind
toTrue
Another way is to use a generator expression to squash the
for
into a single loopYou may also consider using
itertools.product
使用函数进行重构,以便您可以在找到“宾果游戏”时返回。
允许显式打破嵌套循环的提议已被拒绝:
http://www.python.org/dev/peps/pep-3136/
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/
大多数时候,您可以使用多种方法来创建一个与双循环执行相同操作的单循环。
在您的示例中,您可以使用 itertools.product 替换代码片段其他
itertools 函数也适用于其他模式。
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
The other itertools functions are good for other patterns too.