我有这样的词:
[{'number': 44, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'},
{'number': 3, 'code': 'ZXC'}]
如何获得这样的列表:
[{'number': 47, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'}]
答案 0 :(得分:0)
我建议这样做,将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)
答案 1 :(得分:0)
试试这个:
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.