1.send
1 def generato():
2 print('关于send的使用方法')
3 tmp = yield 1
4 print('上面的就是send的应用')
5 print(tmp)
6 yield '现在来测试一下效果吧'
7
8 g = generato()
9 g.__next__()
10 g.send('我们一起学python')
11 # g.send(None)
12 #send 获取下一个值的效果和next基本一致
13 #只是在获取下一个值的时候,给上一yield的位置传递一个数据
14 #使用send的注意事项
15 # 第一次使用生成器的时候 是用next获取下一个值
16 # 最后一个yield不能接受外部的值
2:应用生成器计算移动平均值
1 def averager():
2 total = 0.0
3 count = 0
4 average = None
5 while True:
6 term = yield average
7 total += term
8 count += 1
9 average = total/count
10 g_avg = averager()
11 print(g_avg.__next__())
12 print(g_avg.send(10))
13 print(g_avg.send(30))
14
15 #升级版
16 def init(func):
17 def inner(*args,**kwargs):
18 g = func(*args, **kwargs)
19 next(g)
20 return g
21 return inner
22
23 @init
24 def averager():
25 total = 0.0
26 count = 0
27 average = None
28 while True:
29 term = yield average
30 total += term
31 count += 1
32 average = total/count
33 g_avg = averager()
34 print(g_avg.__next__())
35 print(g_avg.send(10))
36 print(g_avg.send(30))
3.列表推导式和生成器表达式
egg_list = ['鸡蛋%s' %i for i in range(10)] #列表解析
laomuji = ('鸡蛋%s' %i for i in range(10)) #生成器表达式
print(laomuji)
print(next(laomuji)) #和__next__一样
print(laomuji.__next__())
print(next(laomuji))
'''
鸡蛋0
鸡蛋1
鸡蛋2
'''