计算比例

 1 def read_data():
 2     with open("test","r",encoding="utf-8") as f :
 3         for data in f:
 4             yield data
 5 
 6 g = read_data()
 7 
 8 all_population = sum(eval(dt)["population"] for dt in g)
 9 print(all_population )
10 
11 g1 = read_data()
12 
13 for res in g1:
14     data_pic = eval(res)
15     print("%s所占全部的比例是%.1f"%(data_pic["city"],round(data_pic["population"]/all_population,3) *100))
文件如下:

{"city":"北京","population":56}
{"city":"上海","population":28}
{"city":"南京","population":30}
{"city":"安徽","population":40}
{"city":"台湾","population":100}
posted @ 2018-07-28 08:56  沧海一粒水  阅读(214)  评论(0编辑  收藏  举报