给定以下代码(不起作用):
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
使用numpy.ndindex可以简单地将多个循环转换为单个、可破坏的循环
for i in range(n):
for j in range(n):
val = x[i, j]
break # still inside the outer loop!
for i, j in np.ndindex(n, n):
val = x[i, j]
break # you left the only loop there was!
您确实需要索引到对象中,而不是显式地遍历值,但至少在简单的情况下,它似乎比大多数答案所建议的要简单大约2-20倍。
从语言层面上没有办法做到这一点。有些语言
一个goto其他人有一个需要争论的休息,python没有。
最好的选择是:
设置一个由外部循环检查的标志,或设置外部循环
循环条件。
将循环放入函数中,并使用return立即跳出所有循环。
重新规划你的逻辑。
这要归功于Vivek Nagarajan,他从1987年开始成为程序员
使用函数
def doMywork(data):
for i in data:
for e in i:
return
使用国旗
is_break = False
for i in data:
if is_break:
break # outer loop break
for e in i:
is_break = True
break # inner loop break