Python yield 小結和執行個體_python

來源:互聯網
上載者:User

一個帶有 yield 的函數就是一個 generator,它和普通函數不同,產生一個 generator 看起來像函數調用,但不會執行任何函數代碼,直到對其調用 next()(在 for 迴圈中會自動調用 next())才開始執行。雖然執行流程仍按函數的流程執行,但每執行到一個 yield 語句就會中斷,並返回一個迭代值,下次執行時從 yield 的下一個語句繼續執行。看起來就好像一個函數在正常執行的過程中被 yield 中斷了數次,每次中斷都會通過 yield 返回當前的迭代值。

yield 的好處:把一個函數改寫為一個 generator 就獲得了迭代能力,比起用類的執行個體儲存狀態來計算下一個 next() 的值,不僅代碼簡潔,而且執行流程異常清晰。

測試代碼:
 

複製代碼 代碼如下:

#!/usr/bin/env python
#-*- coding:utf8 -*-

def fab(max):
    """斐波那契數列"""
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n += 1


def perm(items, n=None):
    """全排列"""
    if n is None:
        n = len(items)
    for i in range(len(items)):
        v = items[i:i+1]
        if n == 1:
            yield v
        else:
            rest = items[:i] + items[i+1:]
            for p in perm(rest, n-1):
                yield v + p

if __name__ == '__main__':
    for n in fab(5):
        print n
    print  "全排列:123"
    for n in perm("123"):
        print n

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.