<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 生成器 通過列表生成式,我們可以直接創建一個列表。但是,受到內存限制,列表容量肯定是有限的。而且,創建一個包含100萬個元素的列表,不僅占用很大的存儲空間,如果我們僅僅需要訪問前面幾個元素,那后面絕大多數元素占用的空間都白白浪費了。 所以,如果列表元素可以按照某種算法推算出來,那我們是否可以在循環的過程中不斷推算出后續的元素呢?這樣就不必創建完整的list,從而節省大量的空間。在Python中,這種一邊循環一邊計算的機制,稱為生成器:generator。 要創建一個generator,有很多種方法。第一種方法很簡單,只要把一個列表生成式的`[]`改成`()`,就創建了一個generator: ``` >>> L = [x * x for x in range(10)] >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> g = (x * x for x in range(10)) >>> g <generator object <genexpr> at 0x1022ef630> ``` 創建`L`和`g`的區別僅在于最外層的`[]`和`()`,`L`是一個list,而`g`是一個generator。 我們可以直接打印出list的每一個元素,但我們怎么打印出generator的每一個元素呢? 如果要一個一個打印出來,可以通過`next()`函數獲得generator的下一個返回值: ``` >>> next(g) 0 >>> next(g) 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) 16 >>> next(g) 25 >>> next(g) 36 >>> next(g) 49 >>> next(g) 64 >>> next(g) 81 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration ``` 我們講過,generator保存的是算法,每次調用`next(g)`,就計算出`g`的下一個元素的值,直到計算到最后一個元素,沒有更多的元素時,拋出`StopIteration`的錯誤。 當然,上面這種不斷調用`next(g)`實在是太變態了,正確的方法是使用`for`循環,因為generator也是可迭代對象: ``` >>> g = (x * x for x in range(10)) >>> for n in g: ... print(n) ... 0 1 4 9 16 25 36 49 64 81 ``` 所以,我們創建了一個generator后,基本上永遠不會調用`next()`,而是通過`for`循環來迭代它,并且不需要關心`StopIteration`的錯誤。 generator非常強大。如果推算的算法比較復雜,用類似列表生成式的`for`循環無法實現的時候,還可以用函數來實現。 比如,著名的斐波拉契數列(Fibonacci),除第一個和第二個數外,任意一個數都可由前兩個數相加得到: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... 斐波拉契數列用列表生成式寫不出來,但是,用函數把它打印出來卻很容易: ``` def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done' ``` 上面的函數可以輸出斐波那契數列的前N個數: ``` >>> fib(6) 1 1 2 3 5 8 'done' ``` 仔細觀察,可以看出,`fib`函數實際上是定義了斐波拉契數列的推算規則,可以從第一個元素開始,推算出后續任意的元素,這種邏輯其實非常類似generator。 也就是說,上面的函數和generator僅一步之遙。要把`fib`函數變成generator,只需要把`print(b)`改為`yield b`就可以了: ``` def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' ``` 這就是定義generator的另一種方法。如果一個函數定義中包含`yield`關鍵字,那么這個函數就不再是一個普通函數,而是一個generator: ``` >>> f = fib(6) >>> f <generator object fib at 0x104feaaa0> ``` 這里,最難理解的就是generator和函數的執行流程不一樣。函數是順序執行,遇到`return`語句或者最后一行函數語句就返回。而變成generator的函數,在每次調用`next()`的時候執行,遇到`yield`語句返回,再次執行時從上次返回的`yield`語句處繼續執行。 舉個簡單的例子,定義一個generator,依次返回數字1,3,5: ``` def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) ``` 調用該generator時,首先要生成一個generator對象,然后用`next()`函數不斷獲得下一個返回值: ``` >>> o = odd() >>> next(o) step 1 1 >>> next(o) step 2 3 >>> next(o) step 3 5 >>> next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration ``` 可以看到,`odd`不是普通函數,而是generator,在執行過程中,遇到`yield`就中斷,下次又繼續執行。執行3次`yield`后,已經沒有`yield`可以執行了,所以,第4次調用`next(o)`就報錯。 回到`fib`的例子,我們在循環過程中不斷調用`yield`,就會不斷中斷。當然要給循環設置一個條件來退出循環,不然就會產生一個無限數列出來。 同樣的,把函數改成generator后,我們基本上從來不會用`next()`來獲取下一個返回值,而是直接使用`for`循環來迭代: ``` >>> for n in fib(6): ... print(n) ... 1 1 2 3 5 8 ``` 但是用`for`循環調用generator時,發現拿不到generator的`return`語句的返回值。如果想要拿到返回值,必須捕獲`StopIteration`錯誤,返回值包含在`StopIteration`的`value`中: ``` >>> g = fib(6) >>> while True: ... try: ... x = next(g) ... print('g:', x) ... except StopIteration as e: ... print('Generator return value:', e.value) ... break ... g: 1 g: 1 g: 2 g: 3 g: 5 g: 8 Generator return value: done ``` 關于如何捕獲錯誤,后面的錯誤處理還會詳細講解。 ## 練習 [楊輝三角](http://baike.baidu.com/view/7804.htm)定義如下: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 ``` 把每一行看做一個list,試寫一個generator,不斷輸出下一行的list: ``` # -*- coding: utf-8 -*- def triangles(): pass # 期待輸出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] n = 0 for t in triangles(): print(t) n = n + 1 if n == 10: break ``` ## 小結 generator是非常強大的工具,在Python中,可以簡單地把列表生成式改成generator,也可以通過函數實現復雜邏輯的generator。 要理解generator的工作原理,它是在`for`循環的過程中不斷計算出下一個元素,并在適當的條件結束`for`循環。對于函數改成的generator來說,遇到`return`語句或者執行到函數體最后一行語句,就是結束generator的指令,`for`循環隨之結束。 請注意區分普通函數和generator函數,普通函數調用直接返回結果: ``` >>> r = abs(6) >>> r 6 ``` generator函數的“調用”實際返回一個generator對象: ``` >>> g = fib(6) >>> g <generator object fib at 0x1022ef948> ``` ## 參考源碼 [do_generator.py](https://github.com/michaelliao/learn-python3/blob/master/samples/advance/do_generator.py)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看