1. 程式人生 > >python-day17--生成器

python-day17--生成器

line seek pan 文本 ext 讀取文件 ont next name

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 time
def 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)) #傳值 next
print(avg.send(20))
5.傳值:
#計算移動平均值
def wrap(func):
    def inner(*args,**kwargs):
g = func(*args,**kwargs)
next(g)
return g
return inner

@wrap
def 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)






python-day17--生成器