我想根据另一个键值对字典列表中的一个值求和。
stackOverflow 的问题答案更简单,只需对总值求和即可: I have a very big list of dictionaries and I want to sum the insides
例如:如果我们有
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 新手。
最佳答案
使用字典来追踪每年的降雪量;一个collections.defaultdict()
object在这里很理想:
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)。它会为您汇总每年的值(value)。
最后几行创建您想要的结构,按年份降序排列。
演示:
>>> 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}]
关于python - 基于字典中的一个键的字典列表中的一个值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22771528/