2、生成器表达式
li = [i for i in range(10)]
print (li)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
li_iter= (i for i in range(10))
print (li_iter)
#<generator object <genexpr> at 0x0025B470>
1、函数式的生成器 yield
#只要函数内部包含有yield关键字,那么函数名()的到的结果就是生成器,并且不会执行函数内部代码
def func():
print('====>first')
yield 1
print('====>second')
yield 2
print('====>third')
yield 3
print('====>end')
g=func()
print(g) #<generator object func at 0x0000000002184360>
#这里只是拿到了生成器 还没有运行函数的
使用 next 就可以执行函数
#yield 运行一次next 就保存上一次的运行状态,下一次再运行 就从上一次保存状态往下运行
直到不能执行next 方法 收到 stopitererror 的错误报告为止
只能往前不能后退
可以单步debug 查看函数的运行
3、包子模型
li = list(range(10))
print (li)
1 # coding=utf-8
2 def product_baozi():
3 ret = []
4 for i in range(100):
5 ret.append("一笼包子%s" % i)
6 return (ret)
7
8
9 re = product_baozi()
10 print(re)
11
12 # 这就是用所有资源 把包子全部做出来再卖
13
14 baozi = ("一笼包子%s" % i for i in range(100))
15 print(baozi)
16
17
18 # 这个是表达式的生成器形式
19
20 # 可以做一笼卖一笼
21 def product_baozi():
22 for i in range(100):
23 yield "一笼包子%s" % i
24
25
26 baozi = product_baozi()
27 # 这个就是函数式的生成器
28 print(baozi)
29
30
31 def chi_baozi(baozi):
32 yield "来了一个人吃了%s" % baozi
33
34
35 print(chi_baozi(baozi.__next__()).__next__())
36 print(chi_baozi(baozi.__next__()).__next__())
37 print(chi_baozi(baozi.__next__()).__next__())
38 print(chi_baozi(baozi.__next__()).__next__())
#函数生成器 就是可以保持函数当前运行状态,下一次运行就从当前状态运行
4、for循环也能够 循环生成器
1 #coding=utf-8
2 def xiadan():
3 for i in range(1000):
4 yield "鸡蛋%s"%i
5 lmj = xiadan()
6 print (lmj)
7 for index,jidan in enumerate(lmj):
8 print ("第%s个人的%s"%(index,jidan#coding=utf-8
求 人口 占比
# test
# {"name":"北京","population":10}
# {"name":"四川","population":30}
# {"name":"台湾","population":20}
# {"name":"香港","population":40}
# {"name":"澳门","population":50}
with open("test","r",encoding="utf-8") as f:
sum_pop=sum(eval(i)["population"] for i in f)
def get_pop(file):
with open(file, "r", encoding="utf-8") as f:
for i in f:
yield i
data = get_pop("test")
for i in data:
dic=(eval(i))
print ("%s占比%s %%"%(dic["name"],(dic["population"])/sum_pop))
# 北京占比0.06666666666666667 %
# 四川占比0.2 %
# 台湾占比0.13333333333333333 %
# 香港占比0.26666666666666666 %
# 澳门占比
0.3333333333333333 %