假设a.txt记录人口普查数据:
{'name':'北京','population':100}
{'name':'天津','population':150}
{'name':'上海','population':200}
{'name':'深圳','population':250}
{'name':'广州','population':300}
统计人口总数,以及各城市人口比例,代码如下:
def population(): with open('a.txt','r',encoding='utf8') as f: for p in f: yield p iter1 = population() all_population = sum(eval(i)['population'] for i in iter1) print('总人口:',all_population) iter2 = population() for j in iter2: name = eval(j)['name'] population = eval(j)['population'] percent = str(population/all_population*100)+'%' print(name,population,percent)
显示结果如下:
总人口: 1000
北京 100 10.0%
天津 150 15.0%
上海 200 20.0%
深圳 250 25.0%
广州 300 30.0%