簡體   English   中英

基於字典中的一個鍵的字典列表中一個值的總和

[英]sum of one value in the list of dictionary based on one key in dict

我想根據另一個鍵值等於等於字典列表中的一個值。

只求總值的總和就容易了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的新手。

使用字典來追蹤每年的降雪量; 一個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}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM