![](/img/trans.png)
[英]Python list/dict comprehension summing a dict list key by another key in the same dict
[英]Python 2, summing the same values in list of dict
我有字典,像这样:
[{'number': 44, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'},
{'number': 3, 'code': 'ZXC'}]
我怎样才能得到这样的列表:
[{'number': 47, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'}]
我建议这样做,将 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)
尝试这个:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.