给定以下代码(不起作用):
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
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
如果您只需要在复杂的for循环巢中测试边缘情况,则可以抛出1/0来引发异常。我保证不会告诉任何人。当您希望快速测试深度嵌套的for循环的单个迭代,并且不想跟踪大量break语句或注释掉大量代码时,这种方法非常方便。
是的,您可以将它包装在函数中并使用return,但在某些上下文中,这可能会非常麻烦。
入门级程序员的例子:
for i in first_iter:
for j in second_iter:
for k in third_iter:
print(i_want_to_run_this_once_and_stop_executing(i,j,k))
1/0
code_that_takes_a_long_time()
expensive_code()
在执行大量数据预处理的大型jupyter笔记本脚本中,这尤其方便。
使用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倍。
首先,普通的逻辑是有用的。
如果由于某种原因,终止条件无法确定,例外是一个后备计划。
class GetOutOfLoop( Exception ):
pass
try:
done= False
while not done:
isok= False
while not (done or isok):
ok = get_input("Is this ok? (y/n)")
if ok in ("y", "Y") or ok in ("n", "N") :
done= True # probably better
raise GetOutOfLoop
# other stuff
except GetOutOfLoop:
pass
对于这个特定的示例,可能不需要异常。
另一方面,在字符模式应用程序中,我们经常有“Y”、“N”和“Q”选项。对于"Q"选项,我们要立即退出。这是比较特殊的。