如何打破Python中的嵌套循环? [英] How to break nested for loop in Python?
问题描述
我想知道如何从这样的循环中退出:
I wonder how to get out from loop like this:
for a in range(95):
for b in range(95):
for c in range(95):
for d in range(95):
...
do some computings
...
if condition:
task completed
任务完成后,所有循环和计算将继续.它们必须被破坏,但我不知道如何-任务完成"之后的单个break语句将仅在最内层的for循环结束,但是它将被多次调用-因此我们一无所获.
After task is completed all loops and computings are continued. They have to be broke but I don't know how - single break statement after "task completed" will end only innermost for loop but it will be invoked again multiple times - so we gain nothing.
在C语言中,我会执行a = b = c = d = 95,但在python中则行不通.当然,我可以改用while循环,但是然后我必须使用X + = 1语句,这看起来很糟糕.
In C I would do a=b=c=d=95 but in python that wouldn't work. Of course I can use while loop instead but then I have to use X+=1 statements and it would look awful.
有帮助吗?
Any help?
关于循环: 我用它使用蛮力破解了一个4字符的密码.这不是真正的目的-仅用于测试.
About the loop: I use it to break a 4-char password using brute-force. It isn't a real purpose - used only for tests.
推荐答案
使用itertools产品:
Using itertools product:
from itertools import product
for a, b, c, d in product(range(95), range(95), range(95), range(95)):
print a, b, c, d
if a == 1: break
更短的版本,感谢Ashwini:
Shorter version, thanks Ashwini:
for a, b, c, d in product(range(95), repeat=4):
print a, b, c, d
if a == 1: break
这篇关于如何打破Python中的嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!