我试图弄清楚如何打破嵌套的 for 循环以实现以下目标:
- 当它打破嵌套的 for 循环时,它仍然在外部 for 循环内
- 当它中断嵌套的 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")
有更好的方法吗?