1.本质:就是迭代器
2.生成器函数:
def func(): a=1 b=2 yield a #返回第一个值 yield b #返回第二个值
ret = func() #拿到一个生成器print(next(ret)) #取第一个值print(next(ret)) #取第二个值print(next(ret)) #取第三个值 会报错 因为没有第三个值 3.生成器监听文件输入的例子
import timedef tail(filename): with open(filename) as f: f.seek(0, 2) #从文件末尾算起 while True: line = f.readline() # 读取文件中新的文本行 if not line: time.sleep(0.1) continue yield line print(next(tail(‘tmp_file‘))) 4.#计算移动平均值
def averager(): total = 0 day = 0 avrage = 0 while True: day_num = yield avrage #return avrage total += day_num day += 1 avrage = total/day avg = averager()num = next(avg) #激活生成器 avg.send(),什么都不send和next效果一样print(avg.send(10)) #传值 nextprint(avg.send(20))
5.传值:
#计算移动平均值def wrap(func):
def inner(*args,**kwargs): g = func(*args,**kwargs) next(g) return g return inner @wrapdef averager(): total = 0 day = 0 avrage = 0 while True: day_num = yield avrage #return avrage total += day_num day += 1 avrage = total/day g = averager()print(g.send(10))print(g.send(20))
6.
def func(): # for i in ‘AB‘: # yield i yield from ‘AB‘ yield from [1,2,3]g = func()l = []l.append(next(g))l.append(next(g))l.append(next(g))l.append(next(g))l.append(next(g))print(l)
时间: 2024-10-11 20:42:03