python - 基于字典中的一个键的字典列表中的一个值的总和

标签 python list python-3.x dictionary

我想根据另一个键值对字典列表中的一个值求和。

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/

相关文章:

Java 从 List<List<float[]>> 中删除重复项

python - 如何使用 python 自动制作字典?

python - 在不抑制和操纵 pylint 设置的情况下控制 "too many local variable in a function"的最佳做法是什么?

javascript - 将 MySQL 查询结果传递给 Django 中的 Javascript/Jquery

python - VS 代码中的外部终端调试器

python - 子类化时如何不必在 init 中键入 self

一次添加更多元素的Python列表理解

python - 在数组中搜索关键字-python

python - 如何在单元测试期间验证 Mock mock_calls 列表中的 .__getitem__() 调用

python - 如何修复Python中的 'TypeError: argument of type '函数“不可迭代”