简体   繁体   English

将某些元素作为列表的字典列表中的求和值

[英]Sum Values in List of Dictionaries with some elements as list

I have this list of dictionaries:我有这个字典列表:


list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':5}, {'A':1,'B':1,'C':1,'D':1,'E':1}, {'A':2,'B':2,'C':2,'D':2,'E':2}]

To sum up values, I can use counter like this:总结价值,我可以像这样使用计数器:

from collections import Counter
import functools, operator
# sum the values with same keys
counter = Counter()
for d in list_of_dicts: 
    counter.update(d)
      
result = dict(counter) 
result
{'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': 8}

But how to achieve summation if some key in the dictionary has value as list:但是如果字典中的某个键具有列表值,如何实现求和:

list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':[1,2,3]}, {'A':1,'B':1,'C':1,'D':1,'E':[1,2,3]}, {'A':2,'B':2,'C':2,'D':2,'E':[1,2,3]}]

I want to get this result:我想得到这个结果:

{'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E':[3,6,9]}

If you can not use numpy you can try this:如果你不能使用numpy你可以试试这个:

(using collections.defaultdict ) (使用collections.defaultdict

from collections import defaultdict
list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':[1,2,3]}, 
                 {'A':1,'B':1,'C':1,'D':1,'E':[1,2,3]}, 
                 {'A':2,'B':2,'C':2,'D':2,'E':[1,2,3]}]

dct = defaultdict(list)
for l in list_of_dicts:
    for k,v in l.items():
        dct[k].append(v)
        
for k,v in dct.items():
    if isinstance(v[0],list):
        dct[k] = [sum(x) for x in zip(*v)]
    else:
        dct[k] = sum(v)

Output:输出:

>>> dct
defaultdict(list, {'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': [3, 6, 9]})

If you can use numpy you can try this:如果你可以使用numpy你可以试试这个:

import numpy as np

dct = defaultdict(list)
for l in list_of_dicts:
    for k,v in l.items():
        dct[k].append(v)

for k,v in dct.items():
    dct[k] = (np.array(v).sum(axis=0))

Output:输出:

>>> dct
defaultdict(list, {'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': array([3, 6, 9])})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM