生成器屬於可迭代對象的一種。後者範圍更大一些,包括元組、字符串、列表、集合、字典等。
生成器是什麼呢?它是推演列表元素的算法。
Python 列表生成器與lambda函數容易混淆。如下所示,creator_li是列表生成器,把()變成[],creator_li就會變成列表生成式了。
li = [1,2,3,5,5,6,7,8,9,9,8,3]
lambda_li = list(map(lambda x:x*2, li))
creator_li = (x*2 for x in li)
print(creator_li.__next__())
調用next(creator_li)也可以獲得列表生成器的下一個值。當 li 沒有更多的元素時,next(creator_li)會拋出異常:StopIteration.
使用next()會報錯,使用for循環不會報錯。
g = (x * x for x in range(10))
for n in g:print(n)
生成器的另一種實現方法是:用yield關鍵字使一個函數變身爲生成器。
def double_number():
m_list = []
for m in range(10):
tmp = m * 2
m_list.append(tmp)
yield m
print('____in the end of for')
x = double_number()
print(x)
for i in x : print(i)
輸出:
<generator object double at 0x00000000028EF390>
0
____in the end of for
1
____in the end of for
2
____in the end of for
3
____in the end of for
4
____in the end of for
5
____in the end of for
6
____in the end of for
7
____in the end of for
8
____in the end of for
9
____in the end of for
對於x來說,它是一個生成器。如果每次調用next(),執行for循環裏的語句,遇到yield暫停,返回調用處,再次調用next(),從yield的下一行繼續執行到yield處返回。此時,yield相當於return,但是隻有返回調用處的功能,外面拿不到它的返回值。