yield
,到 yield
後回傳,等到下次的呼叫才會繼續執行後續next()
來取值,若使用 while 迴圈就會搭配一個判斷式避免無限迴圈def a():
yield 3
print("now 3")
yield 2
print("now 2")
b = a()
print(b)
# generator object
# 一個產生器的物件
print(next(b))
3
# 利用 next() 到第一個 yield 後跳出
print(next(b))
now 3
2
# 繼續執行後續,印出 now 3
# 到第二個 yield 後跳出
c = a()
for i in c:
print("i", i)
i 3
now 3
i 2
now 2
# 利用 for 迴圈把資料逐一印出
def g(max):
n = 0
a = 2
while n<max:
print("n", n)
yield(a)
a = a * 2
n = n + 1
f = g(3)
print(f)
# generator object
# 一個產生器的物件
print(next(f))
# n 0
# 2
print(next(f))
# n 1
# 4
print(next(f))
# n 2
# 8
print(next(f))
# 跳錯,超過範圍
# most recent call last
yield from
來將多個產生器串在一起def subgen(x):
for i in range(x):
print("sub", i)
yield i
def gen(y):
print("gen")
yield from subgen(y)
for g in gen(3):
print(g)
# gen
# 後續因 yield from 而進入 subgen()
# sub 0
# 0
# sub 1
# 1
# sub 2
# 2
來談談 lambda(匿名函式)