def getpopulation():
with open('a.txt',encoding='utf-8') as f:
for i in f:
yield i
getP = getpopulation()
getPnum = eval(getP.__next__())
print(getPnum['population'])
def getpopulation():
with open('a.txt',encoding='utf-8') as f:
for i in f:
yield i
getP = getpopulation()
all_pop = sum(eval(i)['population'] for i in getP) #获取总人数
print(all_pop)
#注意:迭代只能迭代一次,这里getP在上边已经迭代过了,所以下面的for循环不能在使用
#可以重新赋值给两一个变量
for i in getP:
print('%s %%' %eval(i)['population']/all_pop)
#yield 相当于return 控制的是函数的返回值
#x=yield的另外一个特性,接收send传过来的值赋给x
def test():
print('开始了')
fisrt = yield 1
print('第一次',fisrt)
yield 2
print('第二次')
t = test()
res = t.__next__()
print(res)
t.send(None) #可以触发生成器执行
res = t.send('函数停留在哪儿,我就在哪儿赋值') #可以触发生成器执行
print(res)