W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你想遍歷一個可迭代對象中的所有元素,但是卻不想使用for循環(huán)。
為了手動的遍歷可迭代對象,使用 next()
函數(shù)并在代碼中捕獲 StopIteration
異常。比如,下面的例子手動讀取一個文件中的所有行:
def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line = next(f)
print(line, end='')
except StopIteration:
pass
通常來講,StopIteration
用來指示迭代的結(jié)尾。然而,如果你手動使用上面演示的 next()
函數(shù)的話,你還可以通過返回一個指定值來標記結(jié)尾,比如None。下面是示例:
with open('/etc/passwd') as f:
while True:
line = next(f)
if line is None:
break
print(line, end='')
大多數(shù)情況下,我們會使用for循環(huán)語句用來遍歷一個可迭代對象。但是,偶爾也需要對迭代做更加精確的控制,這時候了解底層迭代機制就顯得尤為重要了。
下面的交互示例向我們演示了迭代期間所發(fā)生的基本細節(jié):
>>> items = [1, 2, 3]
>>> # Get the iterator
>>> it = iter(items) # Invokes items.__iter__()
>>> # Run the iterator
>>> next(it) # Invokes it.__next__()
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
本章接下來幾小節(jié)會更深入的講解迭代相關(guān)技術(shù),前提是你先要理解基本的迭代協(xié)議機制。所以確保你已經(jīng)把這章的內(nèi)容牢牢記在心中。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: