python循环迭代_Python中循环迭代的重做
不,Python不直接支持redo。有一個選項可能會讓嵌套循環變得非常糟糕,比如: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
但這意味著,在“redoable”塊中,不訴諸異常、標記變量或將整個東西打包為函數,就不可能break使用外部循環。
或者,使用一個直接的while循環來復制for循環為您做的事情,顯式地創建和推進迭代器。它有自己的問題(continue實際上是redo默認情況下,您必須顯式地為“real”continue推進迭代器),但它們并不可怕(只要您使用continue注釋,以表明您打算redo對continue,以避免混淆維護者)。要允許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)
上面的操作也可以用try/except StopIteration:來完成,而不是用一個sentinel來包裝兩個參數next,但是用它來包裝整個循環可能會有其他StopIteration源被捕獲的風險,并且在一個有限的范圍內對內部和外部的next調用都正確地執行這一操作會非常難看(比基于sentinel的方法更糟糕)。
總結
以上是生活随笔為你收集整理的python循环迭代_Python中循环迭代的重做的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html5录音怎么保存到本地,详解HTM
- 下一篇: python教程简书_Python快速教