2

我试图弄清楚如何打破嵌套的 for 循环以实现以下目标:

  1. 当它打破嵌套的 for 循环时,它仍然在外部 for 循环内
  2. 当它中断嵌套的 for 循环时,它不再执行剩余的代码,在本例中为最后一行。
def for_loop_flow():
    for a in range(0, 2):
        print "a = %s" % a
        for b in range(3, 5):
            print "b = %s" % b
            if b == 4:
                print "XXXXXXXXbreak"
                break
        print("big piece of logic here, when nested for loop breaks, I "
              "don't wanna be here")

现在,我只能想到使用一个标志:

def for_loop_flow():
    for a in range(0, 2):
        print "a = %s" % a
        flag = True
        for b in range(3, 5):
            print "b = %s" % b
            if b == 4:
                print "XXXXXXXXbreak"
                flag = False
                break
        if flag == True:
            print("big piece of logic here, when nested for loop breaks, I "
                  "don't wanna be here")

有更好的方法吗?

4

1 回答 1

8

任何for带有 a 和标志变量的循环break都可以表示为for带有else子句的 a。因此,在您的情况下,您可以摆脱标志并使用:

for a in range(2):
    print "a = {:d}".format(a)
    for b in range(3, 5):
        print "b = {:d}".format(b)
        if b == 4:
            print "BREAK!"
            break
    else:
        print "Only run if no break in inner loop"

请注意,这也适用于while

while check_if_still_true():
    do_work()
    if shall_we_break():
        break
else:
    we_exited_because_check_returned_false()
于 2013-05-26T02:19:59.313 回答