for x in mylist:
while True:
...
if shouldredo:
continue # continue becomes equivalent to redo
...
if shouldcontinue:
break # break now equivalent to continue on outer "real" loop
...
break # Terminate inner loop any time we don't redo
# Create guaranteed unique sentinel (can't use None since iterator might produce None)
sentinel = object()
iterobj = iter(mylist) # Explicitly get iterator from iterable (for does this implicitly)
x = next(iterobj, sentinel) # Get next object or sentinel
while x is not sentinel: # Keep going until we exhaust iterator
...
if shouldredo:
continue
...
if shouldcontinue:
x = next(iterobj, sentinel) # Explicitly advance loop for continue case
continue
...
if shouldbreak:
break
...
# Advance loop
x = next(iterobj, sentinel)
不,Python不直接支持
redo
。有一个选项可能会让嵌套循环变得非常糟糕,比如:但这意味着,在“
redo
able”块中,不诉诸异常、标记变量或将整个东西打包为函数,就不可能break
使用外部循环。或者,使用一个直接的
while
循环来复制for
循环为您做的事情,显式地创建和推进迭代器。它有自己的问题(continue
实际上是redo
默认情况下,您必须显式地为“real”continue
推进迭代器),但它们并不可怕(只要您使用continue
注释,以表明您打算redo
对continue
,以避免混淆维护者)。要允许redo
和其他循环操作,您需要执行以下操作:上面的操作也可以用
try
/except StopIteration:
来完成,而不是用一个sentinel
来包装两个参数next
,但是用它来包装整个循环可能会有其他StopIteration
源被捕获的风险,并且在一个有限的范围内对内部和外部的next
调用都正确地执行这一操作会非常难看(比基于sentinel
的方法更糟糕)。不,没有。我建议使用while循环并将check变量重置为初始值。
我在学习perl时遇到了同样的问题,我找到了这个页面。
遵循perl手册:
以及如何在Python上实现它?? 遵循准则:
Python没有“redo”语法,但是我们可以在一些函数中进行一个“while”循环,直到我们输入列表时得到所需的内容。
相关问题 更多 >
编程相关推荐