- Python進階編程:編寫更高效、優雅的Python代碼
- 劉宇宙 謝東 劉艷
- 457字
- 2021-04-30 12:39:47
4.1.1 手動遍歷迭代器
很多開發人員可能習慣使用for循環遍歷可迭代對象中的所有元素,這樣操作并沒有問題,但效率并不是最高的。其實,不用for循環也可以遍歷可迭代對象中的所有元素。
我們可使用next()函數遍歷可迭代對象并在代碼中捕獲StopIteration異常。下面展示一個讀取文件中所有行的示例,代碼如下:
def manual_iter(): with open('/etc/passwd') as f: try: while True: line = next(f) # end 指定為 空,輸出行不會有一個空白行 print(line, end='') except StopIteration: pass
上述代碼中,StopIteration用來指示迭代的結尾。next()函數可以通過返回一個指定值來標記結尾,如None或空字符,示例如下:
with open('/etc/passwd') as f: while True: line = next(f, None) if not line: break # end 指定為 空,輸出行不會有一個空白行 print(line, end='')
很多時候,我們會習慣使用for循環語句來遍歷一個可迭代對象。但當需要對迭代做更加精確的控制時,了解底層迭代機制就顯得尤為重要了。
下面示例演示了迭代的一些基本細節,代碼(hands_iter.py)如下:
num_list = [1, 2, 3] items = iter(num_list) for i in range(len(num_list)): print(f'first items next is:{next(items)}') for i in range(len(num_list) + 1): print(f'second items next is:{next(items)}')
執行py文件,輸出結果如下:
first items next is:1 first items next is:2 first items next is:3 second items next is:1 second items next is:2 second items next is:3 Traceback (most recent call last): File "/advanced_programming/chapter4/hands_iter.py", line 27, in <module> print(f'second items next is:{next(items)}') StopIteration
比對輸出結果,查看第一個循環輸出和第二個循環輸出的結果,可以發現第二個循環拋出異常了。
推薦閱讀