我想添加相同ID的值
例如:在以下数据中,' 6'有两个值('6', 0.8556180596351624)
和('6', 0.864041805267334)
。
我想总结一下('6', 1.7196598649025)
[('6', 0.8556180596351624), ('10', 0.8263003826141357), ('3', 0.8221487998962402), ('5', 0.8209285140037537), ('21', 0.8116759061813354), ('13', 0.798694372177124), ('16', 0.7894450426101685), ('17', 0.788898766040802), ('2', 0.7756567001342773), ('9', 0.7618461847305298), ('6', 0.864041805267334)
我怎么能这样做?建议请。
答案 0 :(得分:2)
使用collections.defaultdict
根据项目的第一个值对项目进行分类,然后将重复项目的第二个值相加:
In [22]: from collections import defaultdict
In [24]: d = defaultdict(int)
In [25]: lst = [('6', 0.8556180596351624), ('10', 0.8263003826141357), ('3', 0.8221487998962402), ('5', 0.8209285140037537), ('21', 0.8116759061813354), ('13', 0.798694372177124), ('16', 0.7894450426101685), ('17', 0.788898766040802), ('2', 0.7756567001342773), ]
In [26]: for i, j in lst:
....: d[i] += j
....:
In [27]: d.items()
Out[27]:
[('10', 0.8263003826141357),
('13', 0.798694372177124),
('21', 0.8116759061813354),
('17', 0.788898766040802),
('16', 0.7894450426101685),
('3', 0.8221487998962402),
('2', 0.7756567001342773),
('5', 0.8209285140037537),
('6', 1.7196598649024963),
('9', 0.7618461847305298)]
答案 1 :(得分:0)
假设您想要所有唯一值,我会使用defaultdict()
:
import collections
d = ... your list ...
cd = collections.defaultdict(int)
for key, value in d: cd[key] += value
print cd["6"]
打印1.7196598649024963。