请教将一个列表中字典字段相同的元素合并并且值相加,有什么好的办法吗?

如下两个列表,需要将oldList转化为newList,去掉相同字段的字典,并且去掉的参数里面的值要相加

oldList = [{'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1972}, {'3-3': 203, '3-2': 0, '3-1': 0, '3-0': 0}, {'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1450}, {'3-3': 203, '3-2': 0, '3-1': 0, '3-0': 0}, {'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1334}]

newList = [{'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 4756}, {'3-3': 406, '3-2': 0, '3-1': 0, '3-0': 0}]

你好,我写了一种方式供你参考,希望可以帮到你。

import operator

oldList = [{'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1972},
           {'3-3': 203, '3-2': 0, '3-1': 0, '3-0': 0},
           {'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1450},
           {'3-3': 203, '3-2': 0, '3-1': 0, '3-0': 0},
           {'0-0': 0, '0-1': 0, '0-2': 0, '0-3': 1334}]

newList = []

# 先把oldList第一个元素给newList,防止下面for循环中newList为空
newList.append(oldList[0])

# 每给newList添加一个元素时都和前面的比较,若keys()相同,则合并
for t in range(1,len(oldList)):
    for li in newList:
        if operator.eq(li.keys(), oldList[t].keys()):
            for key in li.keys():
                li[key] += oldList[t][key]
            break
        # 若keys()都不相同,则把新元素添加到newList
        elif operator.eq(li,newList[-1]):
            newList.append(oldList[t])
            break

print(newList)

可以拿去直接用

def sum_dict(a,b):
    temp = dict()
    for key in a.keys()| b.keys():
        temp[key] = sum([d.get(key, 0) for d in (a, b)])
    return temp

def main():
    from functools import reduce
    return print(reduce(sum_dict,[a,b,c]))

a = {'f': 1, 't': 2, 'u': 3}
b = {'f':1,'g':3,'d':4}
c = {'g':3,'f':5,'e':10}
main()

看不懂这里有注释。
https://www.cnblogs.com/banxiancode/p/12101467.html