1. <b id="gxlhv"><p id="gxlhv"></p></b>
      2. <video id="gxlhv"></video>

        <u id="gxlhv"><address id="gxlhv"></address></u>
      3. python世界

        Python3 迭代器與生成器

        本文發布日期:2020-08-01 23:56:40

        迭代是Python最強大的功能之一,是訪問集合元素的一種方式。

        迭代器是一個可以記住遍歷的位置的對象。

        迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會后退。

        迭代器有兩個基本的方法:iter() 和 next()。

        字符串,列表或元組對象都可用于創建迭代器:

        實例(Python 3.0+)

        >>> list=[1,2,3,4]
        >>> it = iter(list)    # 創建迭代器對象
        >>> print (next(it))   # 輸出迭代器的下一個元素
        1
        >>> print (next(it))
        2
        >>> 

        迭代器對象可以使用常規for語句進行遍歷:

        實例(Python 3.0+)

        #!/usr/bin/python3 list=[1,2,3,4] it = iter(list) # 創建迭代器對象 for x in it: print (x, end=" ")

        執行以上程序,輸出結果如下:

        1 2 3 4

        也可以使用 next() 函數:

        實例(Python 3.0+)

        #!/usr/bin/python3 import sys # 引入 sys 模塊 list=[1,2,3,4] it = iter(list) # 創建迭代器對象 while True: try: print (next(it)) except StopIteration: sys.exit()

        執行以上程序,輸出結果如下:

        1
        2
        3
        4

        創建一個迭代器

        把一個類作為一個迭代器使用需要在類中實現兩個方法 __iter__() 與 __next__() 。

        如果你已經了解的面向對象編程,就知道類都有一個構造函數,Python 的構造函數為 __init__(), 它會在對象初始化的時候執行。

        更多內容查閱:Python3 面向對象

        __iter__() 方法返回一個特殊的迭代器對象, 這個迭代器對象實現了 __next__() 方法并通過 StopIteration 異常標識迭代的完成。

        __next__() 方法(Python 2 里是 next())會返回下一個迭代器對象。

        創建一個返回數字的迭代器,初始值為 1,逐步遞增 1:

        實例(Python 3.0+)

        class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter))

        執行輸出結果為:

        1
        2
        3
        4
        5

        StopIteration

        StopIteration 異常用于標識迭代的完成,防止出現無限循環的情況,在 __next__() 方法中我們可以設置在完成指定循環次數后觸發 StopIteration 異常來結束迭代。

        在 20 次迭代后停止執行:

        實例(Python 3.0+)

        class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)

        執行輸出結果為:

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20

        生成器

         

        在 Python 中,使用了 yield 的函數被稱為生成器(generator)。

        跟普通函數不同的是,生成器是一個返回迭代器的函數,只能用于迭代操作,更簡單點理解生成器就是一個迭代器。

        在調用生成器運行的過程中,每次遇到 yield 時函數會暫停并保存當前所有的運行信息,返回 yield 的值, 并在下一次執行 next() 方法時從當前位置繼續運行。

        調用一個生成器函數,返回的是一個迭代器對象。

        以下實例使用 yield 實現斐波那契數列:

        實例(Python 3.0+)

        #!/usr/bin/python3 import sys def fibonacci(n): # 生成器函數 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一個迭代器,由生成器返回生成 while True: try: print (next(f), end=" ") except StopIteration: sys.exit()

        執行以上程序,輸出結果如下:

        0 1 1 2 3 5 8 13 21 34 55
        免責聲明:本站部分圖片,文章,均來源于網絡收集,版權歸原作者所有,如有侵權,請與我聯系刪除!
        黄色视频网站在线_狠狠干综合_色欲一区二区_人与嘼AV免费网站
          1. <b id="gxlhv"><p id="gxlhv"></p></b>
          2. <video id="gxlhv"></video>

            <u id="gxlhv"><address id="gxlhv"></address></u>