问题
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
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.
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?
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.
回答1:
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
Shorter version, thanks Ashwini:
for a, b, c, d in product(range(95), repeat=4):
print a, b, c, d
if a == 1: break
回答2:
You can use a exception to break out of nested loops:
class Break(Exception): pass
try:
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
raise Break()
except Break:
# do some stuff
or with StopIteration
:
try:
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
raise StopIteration()
except StopIteration:
# do some stuff
来源:https://stackoverflow.com/questions/25742107/how-to-break-nested-for-loop-in-python