<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                [TOC] # 簡介 利?用迭代器,我們可以在每次迭代獲取數據(通過next()方法)時,按照特定的規律進行生成.但是我們在實現一個迭代器時,關于當前迭代到的狀態需要我們自己記錄,進而才能根據當前狀態生成下一個數據.為了達到當前狀態,并配合next()函數進行迭代使用,我們可以采用更簡便的語法,即生成器(generator).生成器是一類特殊的迭代器 # 分析 通過列表生成式,我們可以直接創建一個列表。但是,受到內存限制,列表容量肯定是有限的。而且,創建一個包含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> ~~~ # next 創建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的錯誤。 # for 當然,上面這種不斷調用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' ~~~ 注意,賦值語句(=號): ~~~ a, b = b, a + b ~~~ 相當于: ~~~ t = (b, a + b) # t是一個tuple a = t[0] b = t[1] ~~~ 但不必顯式寫出臨時變量t就可以賦值。 上面的函數可以輸出斐波那契數列的前N個數: ~~~ >>> fib(6) 1 1 2 3 5 8 'done' ~~~ 仔細觀察,可以看出,fib函數實際上是定義了斐波拉契數列的推算規則,可以從第一個元素開始,推算出后續任意的元素,這種邏輯其實非常類似generator # yield 上面的函數和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 ~~~ # send發送數據 ?用send給yield發送數據 ~~~ def create_num(all_num): a, b = 0, 1 current_num = 0 while current_num < all_num: ret = yield a print('ret>>>', ret) a, b = b, a+b current_num += 1 obj = create_num(10) # 一般不在初始next前調用send,程序會報錯,非要send就傳None吧 # obj.send(None) ret = next(obj) print(ret) # 把數據發給yield ret = obj.send('test') print(ret) ~~~
                  <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>

                              哎呀哎呀视频在线观看