一個函數中需要有一個 yield 語句即可將其轉換為一個生成器。
def frange(start, stop, increment):x = startwhile x < stop:yield xx += incrementfor i in frange(0, 4, 2):print(i) # 0 2
一個生成器函數主要特征是它只會回應在迭代中使用到的 next 操作
def cutdata(n):print("start",n)while n > 0:yield nn-=1print("Done")res=cutdata(3) next(res) next(res) next(res) """ start 3 Done Done"""
?