生成器特性阐释
? #生成器函數一定要next之后才是執行
人口普查: {'name':'北京','population':10}{'name':'山東','population':10}
{'name':'山西','population':31}
{'name':'河北','population':33}
{'name':'臺灣','population':33}
def get_polulation():with open('人口普查', 'r', encoding='utf-8') as f: #打開文件for i in f:yield ig=get_polulation() g.__next__() g.__next__() g.__next__() g.__next__() # print(g.__next__()['population']) #錯誤 因為g.next得到的是字符串 不能直接索引 需要轉化為字典 用eval提取字符串里面的字典 從而索引定位到人口數 # s1=eval(g.__next__()) # print(type(s1)) # print(s1['population']) # res=0 # for p in g: # p_dic=eval(p) # print(p_dic['population']) # res+=p_dic['population'] # print(res) all_pop=sum(eval(i)['population'] for i in g) #總人數 print(all_pop)for p in g:print('%s %%' %eval(p)['population']/all_pop)
?
轉載于:https://www.cnblogs.com/newt/p/9007873.html
總結
- 上一篇: 2018 GDCPC 省赛总结
- 下一篇: [洛谷P1040] 加分二叉树