《Python Cookbook 3rd》笔记(4.1):手动遍历迭代器
生活随笔
收集整理的這篇文章主要介紹了
《Python Cookbook 3rd》笔记(4.1):手动遍历迭代器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
手動遍歷迭代器
問題
你想遍歷一個可迭代對象中的所有元素,但是卻不想使用 for 循環。
解法
為了手動的遍歷可迭代對象,使用 next() 函數并在代碼中捕獲 StopIteration 異常。比如,下面的例子手動讀取一個文件中的所有行:
def manual_iter():with open('/etc/passwd') as f:try:while True:line = next(f)print(line, end='')except StopIteration:pass通常來講, StopIteration 用來指示迭代的結尾。然而,如果你手動使用上面演示的 next() 函數的話,你還可以通過返回一個指定值來標記結尾,比如 None 。下面是示例:
with open('/etc/passwd') as f:while True:line = next(f, None)if line is None:breakprint(line, end='')討論
大多數情況下,我們會使用 for 循環語句用來遍歷一個可迭代對象。但是,偶爾也需要對迭代做更加精確的控制,這時候了解底層迭代機制就顯得尤為重要了。
>>> 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 >>>總結
以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(4.1):手动遍历迭代器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tests1
- 下一篇: 《Python Cookbook 3rd