根据字典中的一个键计算字典列表中某个值的总和
我想根据字典中的一个键的值来计算另一个键的总和。
在StackOverflow上,有个简单的问题回答,教你如何计算总值:我有一个很大的字典列表,我想计算里面的总和
比如说,如果我们有:
lst = [{'year': 2013, 'snow': 64.8, 'month': 1},
{'year': 2013, 'snow': 66.5, 'month': 2},
{'year': 2013, 'snow': 68.3, 'month': 12},
{'year': 2013, 'snow': 68.8, 'month': 3},
{'year': 2013, 'snow': 70.9, 'month': 11},
{'year': 2012, 'snow': 76.8, 'month': 7},
{'year': 2012, 'snow': 79.6, 'month': 5},
{'year': 1951, 'snow': 86.6, 'month': 12}]
要计算那一年降雪的总量:
输出结果应该是:
snowfall = [{'year': 2013, 'totalsnow': 339.3},
{'year': 2012, 'totalsnow': 156.4},
{'year': 1951, 'totalsnow': 86.6}]
这是我的代码:
for i in range(len(lst)):
while lst[i]['year']:
sum(value['snow'] for value in lst)
但是这样会出错,输出是:
582.3000000000001
我该怎么才能正确呢?请简单说明一下,我是Python新手。
1 个回答
4
使用字典来记录每年的降雪量;这里用到的collections.defaultdict()
对象非常合适:
from collections import defaultdict
snowfall = defaultdict(float)
for info in lst:
snowfall[info['year']] += info['snow']
snowfall = [{'year': year, 'totalsnow': snowfall[year]}
for year in sorted(snowfall, reverse=True)]
这段代码首先创建了一个defaultdict()
对象,这个对象会为那些还不存在的键自动生成新的float()
对象(初始值为0.0)。这样,它就能帮你自动计算每年的降雪总量。
最后几行代码会按照年份降序排列,生成你想要的结构。
示例:
>>> from collections import defaultdict
>>> lst = [{'year': 2013, 'snow': 64.8, 'month': 1},
... {'year': 2013, 'snow': 66.5, 'month': 2},
... {'year': 2013, 'snow': 68.3, 'month': 12},
... {'year': 2013, 'snow': 68.8, 'month': 3},
... {'year': 2013, 'snow': 70.9, 'month': 11},
... {'year': 2012, 'snow': 76.8, 'month': 7},
... {'year': 2012, 'snow': 79.6, 'month': 5},
... {'year': 1951, 'snow': 86.6, 'month': 12}]
>>> snowfall = defaultdict(float)
>>> for info in lst:
... snowfall[info['year']] += info['snow']
...
>>> snowfall = [{'year': year, 'totalsnow': snowfall[year]}
... for year in sorted(snowfall, reverse=True)]
>>> from pprint import pprint
>>> pprint(snowfall)
[{'totalsnow': 339.30000000000007, 'year': 2013},
{'totalsnow': 156.39999999999998, 'year': 2012},
{'totalsnow': 86.6, 'year': 1951}]