【问题标题】:Python 2, summing the same values in list of dictPython 2,对 dict 列表中的相同值求和
【发布时间】:2015-12-03 10:40:53
【问题描述】:

我有字典,像这样:

[{'number': 44, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'},     
{'number': 3, 'code': 'ZXC'}]

我怎样才能得到这样的列表:

[{'number': 47, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'}]

【问题讨论】:

  • 以下stackoverflow答案中的场景几乎完全相同。只需创建一个新字典并用总和填充它而不是将它们打印出来:stackoverflow.com/a/18180813/2744166
  • 在这里尝试this代码,用cmets来解释。

标签: python


【解决方案1】:

试试这个:

data=[{'number': 44, 'code': 'ZXC'},{'number': 699, 'code': 'ASD'},{'number': 3, 'code': 'ZXC'}]

from collections import defaultdict

c = defaultdict(int)
for d in data:
    c[d['code']] += d['number']

print [{'number': number, 'code': code} for number, code in c.items()]
#So:
new_list=[{'number': number, 'code': code} for number, code in c.items()]
#In new_list is your list groupped by code and sum applied.

【讨论】:

    【解决方案2】:

    我建议这样做,将 yourList 视为输入列表:

    tempList = list()  
    FinalList()=list()  
    for d in yourList:  
        if d['day'] in tempList:  
            FinalList[tempList.index(d['day'])]['number'] += d['number']  
        else: 
            tempList.append(d['day')]
            FinalList.append(d)
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2020-02-25
      • 2021-11-25
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多