4.1 手動遍歷迭代器

2018-02-24 15:26 更新

問題

你想遍歷一個可迭代對象中的所有元素,但是卻不想使用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)容牢牢記在心中。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號