generator與list比較
- generator:算法實(shí)現(xiàn)下一個(gè)數(shù)據(jù)的輸出,不調(diào)用下一個(gè),就不執(zhí)行下一個(gè)數(shù)據(jù)的運(yùn)算
- list:直接存儲(chǔ)于內(nèi)存,所有數(shù)據(jù)都同時(shí)存在
- generator相較于list占用內(nèi)存小
創(chuàng)建一個(gè)簡(jiǎn)單的generator
- 簡(jiǎn)單的generator的創(chuàng)建:在列表生成式的基礎(chǔ)上將[]改為()
例如:
g=(x*x for x in range(10))
- generator的調(diào)用
- next調(diào)用:(直到報(bào)錯(cuò)結(jié)束)
>>> g=(x*x for x in range(10))
>>> g
<generator object <genexpr> at 0x0610BC00>
>>> next(g)
0
>>>
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
next(g)
StopIteration
>>> def g_get():
for n in g:
print(n)
>>> g=(x*x for x in range(10))
>>> g_get()
0
1
4
9
16
25
36
49
64
81
創(chuàng)建一個(gè)函數(shù)形式的generator
- 函數(shù)型的generator的創(chuàng)建:
與普通函數(shù)不同的是含有關(guān)鍵字yield,即含有yield的函數(shù)就是generator
>>> def yhsj():
L=[1]
while True:
yield L
L=[1]+[L[i]+L[i+1] for i in range(len(L)-1)]+[1]
>>> def get_yhsj():
for n in yhsj():
print(n)
>>> get_yhsj()
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
...
函數(shù)型的generator與普通函數(shù)的不同
- 除了含有yield關(guān)鍵字外,還有就是執(zhí)行順序不同,普通函數(shù)的執(zhí)行是按順序的,而generator是執(zhí)行到y(tǒng)ield語(yǔ)句就停止,知道下一次調(diào)用,執(zhí)行接下來(lái)的語(yǔ)句