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