1. 程式人生 > >Python之yield簡明詳解

Python之yield簡明詳解

yield是Python中的生成器(只能在函式中使用)被稱為generator function(發電機函式),他的作用是將函式中每次執行的結果以類似元組的形式儲存起來一遍後續使用:

示例程式碼:

def sums():
    for j in range(5):
        for k in range(1):
            yield j, k # 迴圈一次yield得到兩個資料
    return j, k


num = sums()
for a in num:  # 遍歷返回的資料
    print(a)

執行結果:

(0, 0)
(1, 0)
(2, 0)
(3, 0)
(4, 0)

例項生成彩票號碼:

"""
輸入注數生成大樂透號碼
紅球取值範圍1-36,籃球1-12
"""
import random


class GreatLotto:
    """
    需要一個生成次數count
    """
    global result  # 宣告全域性變數
    result = []

    def __init__(self, count):
        self.count = count

    def randoms(self):
        """
        :return: 返回傳入次數的隨機彩票號碼(返回的是一個整體列表)
        """
        for i in range(self.count):
            for j in range(7):
                if j <= 4:
                    index1 = random.randrange(1, 36)
                    result.append(index1)
                if j > 4:
                    index1 = random.randrange(1, 13)
                    result.append(index1)
        return result  # 返回生成結果

    def start_end(self):
        """
        :return: 根據傳入的次數判斷列表取值的開始數和結束數
        """
        for k in range(self.count):
            if k < 1:  # 首次開始取值
                start1 = k
            else:
                start1 = k * 7
            end1 = start1 + 7  # 結束值
            yield end1, start1  # yield是生成器,將每次迴圈生成的結果儲存(如果直接使用了return會結束迴圈,導致只能執行一次)


if __name__ == '__main__':
    try:
        num = int(input("請輸入需要生成的注數:"))
    except ValueError:
        print('輸入的格式錯誤!!!')
        num = int(input("請重新輸入需要生成的注數:"))
    Great = GreatLotto(num)  # 例項化GreatLotto 並將輸入的次數傳入
    lists = Great.randoms()  # 得到返回的生成結果
    for end, start in Great.start_end():  # 遍歷函式的生成器
        print(lists[start:end])  # 輸出最終生成的結果

執行結果:
	請輸入需要生成的注數:4
	[10, 5, 8, 26, 12, 10, 8]
	[6, 11, 14, 16, 16, 2, 6]
	[2, 1, 3, 17, 22, 8, 5]
	[19, 27, 28, 29, 9, 7, 7]

小知識
生成器不但可以作用於for迴圈,還可以被next()函式不斷呼叫並返回下一個值,直到最後丟擲StopIteration錯誤表示無法繼續返回下一個值了。