2016-10-19 6 views
0

私は元のために同じ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) 

値を超える合計したいですか?ご提案ください。

答えて

2

使用collections.defaultdictは、重複するもののために第2の値を合計し、その後、彼らの最初の値に基づいてアイテムを分類します

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)] 
0

は、すべての一意の値のためにこれをしたいと仮定すると、私はdefaultdict()を使用したい:

import collections 
d = ... your list ... 
cd = collections.defaultdict(int) 
for key, value in d: cd[key] += value 
print cd["6"] 

これは1.7196598649024963を印刷します。