给定以下代码(不起作用):
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笔记本脚本中,这尤其方便。
我来这里的原因是我有一个外循环和一个内循环,像这样:
for x in array:
for y in dont_use_these_values:
if x.value==y:
array.remove(x) # fixed, was array.pop(x) in my original answer
continue
do some other stuff with x
正如你所看到的,它不会去下一个x,而是去下一个y。
我发现解决这个问题的简单方法是遍历数组两次:
for x in array:
for y in dont_use_these_values:
if x.value==y:
array.remove(x) # fixed, was array.pop(x) in my original answer
continue
for x in array:
do some other stuff with x
我知道这是OP问题的一个具体案例,但我发布它是希望它能帮助人们以不同的方式思考他们的问题,同时保持事情简单。
首先,普通的逻辑是有用的。
如果由于某种原因,终止条件无法确定,例外是一个后备计划。
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"选项,我们要立即退出。这是比较特殊的。