将一个列表中字典字段相同的元素合并并且值相加
1,程序简介
- 如下两个列表,需要将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}]
2,程序代码
"""
Created on Sat Jan 15 19:48:23 2022
Function: 将一个列表中字典字段相同的元素合并并且值相加
@author: 小梁aixj
"""
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 = []
newList.append(oldList[0])
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
elif operator.eq(li,newList[-1]):
newList.append(oldList[t])
break
print(newList)
3,运行结果