How to break nested for loop in Python?

末鹿安然 提交于 2019-12-01 05:28:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!