官术网_书友最值得收藏!

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

比對輸出結果,查看第一個循環輸出和第二個循環輸出的結果,可以發現第二個循環拋出異常了。

主站蜘蛛池模板: 阜平县| 阳春市| 西畴县| 乐昌市| 河池市| 龙井市| 兰考县| 长岭县| 双鸭山市| 平乐县| 郑州市| 惠东县| 三穗县| 屯门区| 汉川市| 龙岩市| 徐州市| 迁安市| 田阳县| 柳河县| 黄陵县| 沁水县| 德州市| 灵寿县| 长治市| 嘉峪关市| 兴海县| 芒康县| 突泉县| 卓资县| 余庆县| 鄢陵县| 华宁县| 子洲县| 芮城县| 东莞市| 峨眉山市| 凤翔县| 枝江市| 额济纳旗| 滨州市|