生成器实例
1 def jidan():
2 for i in range(10):
3 yield'鸡蛋%d' %i
4 #jd:生成器 自动实现迭代器协议
5 jd = jidan()
6 print(jd.__next__())
7 print(jd.__next__())
包子问题:
1 def product_bz():
2 for i in range(10):
3 print('正在生产包子')
4 yield '包子%s'%i
5 print('开始卖包子了')
6 bz_list = product_bz()
7 print(bz_list.__next__())
8 #加代码
9 print(bz_list.__next__())
运行结果:
正在生产包子
包子0
开始卖包子了
正在生产包子
包子1
人口普查:
{'city':'北京','population':23}
{'city':'西安','population':13}
{'city':'上海','population':123}
{'city':'南京','population':12}
{'city':'成都','population':12345}
1 # #获取某一地区的人口数
2 def get_population():
3 with open('人口普查','r',encoding='utf-8') as f:
4 for i in f:
5 yield i
6 print(get_population())
7 get_p = get_population()
8 s = (eval(get_p.__next__()))
9 print(type(s))
10 print(s['population'])
运行结果:
<generator object get_population at 0x02D86270>
<class 'dict'>
23
Process finished with exit code 0
# #使用生成器迭代出所有城市的人口数
def get_population():
with open('人口普查','r',encoding='utf-8') as f:
for i in f:
yield i
print(get_population())
get_p = get_population()
# print(get_p)
for p in get_p:
p_dict = eval(p)
print(p_dict['population'])
运行结果:
<generator object get_population at 0x01376270>
23
13
123
12
12345
Process finished with exit code 0
1 # #计算总人口数
2 def get_population():
3 with open('人口普查','r',encoding='utf-8') as f:
4 for i in f:
5 yield i
6 print(get_population())
7 get_p = get_population()
8 all_pop = sum(eval(i)['population'] for i in get_p)
9 print(all_pop)
运行结果:
<generator object get_population at 0x03716270>
12516
Process finished with exit code 0
1 #计算平均人口数 失败
2 def get_population():
3 with open('人口普查','r',encoding='utf-8') as f:
4 for i in f:
5 yield i
6 print(get_population())#生成器
7 get_p = get_population()
8 all_pop = sum(eval(i)['population'] for i in get_p)
9 print(all_pop)
10 for p in get_p:
11 print(eval(p)['population']/all_pop)#使用__next__()之后所有数字被遍历完 计算平均数失败
运行结果:
<generator object get_population at 0x02F96270>
12516#计算失败
Process finished with exit code 0
#计算失败
Process finished with exit code 0
def test():
for i in range(4):
yield i
t = test()
t1 = (i for i in t)
t2 = (i for i in t1)
print(list(t1))
print(list(t2))#在这之前t1已经遍历过 此时已经遍历结束为空 打印出来空列表
运行结果:
[0, 1, 2, 3]
[]#之前被遍历过 此时为空
Process finished with exit code 0