我本身想寫個可迭代的,——生成器
生成器的本質就是迭代器
所以生成器的全部好處都和迭代器同樣
可是生成器是咱們本身寫的python代碼
生成器的實現有兩種方式:
1.生成器函數
2.生成器表達式html
def func(): return ['衣服1','衣服2000000'] ret = func() print(ret) def g_func(): yield 1 g = g_func() print(g) # <generator object g_func at 0x00000000006AAFC0> generator 生成器 ---> 迭代器 print('__iter__' in dir(g)) # True print('__next__' in dir(g)) # True print(g.__next__()) # 1
生成器函數和普通函數之間的區別
生成器函數中含有yield關鍵字
生成器函數調用的時候不會當即執行,而是返回一個生成器python
def g_func(): print('aaaa') yield 1 print('bbbb') yield 2 g = g_func() for i in g: print(i) # print(g.__next__()) # print(g.__next__()) def cloth(): for i in range(1000000): yield '衣服%s'%i g_cloth = cloth() print(g_cloth.__next__()) print(g_cloth.__next__())
監聽文件末尾追加的例子面試
def tail(): f = open('文件',encoding='utf-8') # print('__iter__' in dir(f)) # True # print('__next__' in dir(f)) # True f.seek(0,2) while True: line = f.readline() if line: yield line import time time.sleep(0.1) g = tail() for i in g: print(i)
send的用法函數
def func(): print('*'*10) a = yield 5 print('a :',a) yield 10 g = func() num = g.__next__() print(num) num2 = g.send('alex') # 至關於next,可是會傳值給yield前的變量 print(num2)
send:從哪個yield開始接着執行,就把一個值傳給了哪一個yield
send不能用在第一個觸發生成器
生成器函數中有多少個yield就必須有多少個next+sendpost
計算移動平均值url
def init(func): # 生成器的預激裝飾器 def inner(*args,**kwargs): g = func(*args,**kwargs) g.__next__() return g return inner @init def averager(): total = 0.0 count = 0 average = None while True: term = yield average total += term count += 1 average = total/count g_avg = averager() # next(g_avg) # g_avg.__next__() print(g_avg.send(10)) print(g_avg.send(30)) print(g_avg.send(5))
yield fromspa
def func(): a = 'AB' b = 'CD' yield from a # 接收一個可迭代對象,至關於下面的for,python3特有 # for i in a: # yield i yield from b # for j in b: # yield j g = func() for i in g: print(i)
生成器函數:生成一個生成器的函數
生成器的本質纔是迭代器
生成器函數的特色:
帶有yield關鍵字,且調用以後,函數內的代碼不執行
觸發執行的方式:
next
send send(None) == __next__()
for循環code
生成器表達式htm
y = [1,2,3,4,5,6,7,8] g = (i**2 for i in y ) print(g) # <generator object <genexpr> at 0x00000000006AAFC0> print(list(g)) # [1, 4, 9, 16, 25, 36, 49, 64] # for i in g: # print(i) l = ['雞蛋%s'%i for i in range(10)] print(l) laomuji = ('雞蛋%s'%i for i in range(10)) for egg in laomuji: print(egg)
面試題對象
def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g1) print(list(g1)) # [0, 1, 2, 3] print(list(g2)) # []
def add(n,i): return n+i def test(): for i in range(4): yield i g=test() for n in [1,10]: g=(add(n,i) for i in g) # n = 1 # g=(add(n,i) for i in test()) # n = 10 # g=(add(10,i) for i in (add(10,i) for i in test())) print(list(g)) # [20, 21, 22, 23]