Python:如何查找重复项并将其值相加?

时间:2015-11-26 01:52:02

标签: python list python-3.x

[('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
例如,我有上面的元组列表,如何找到重复项(即“Visa”)并将它们的值相加(即980.5 + 215.0)?输出应为:

[('Visa', 1195.5), ('Rogers', 61.5)]

6 个答案:

答案 0 :(得分:6)

使用字典:

>>> data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
>>> result = {}
>>> for card,value in data:
        total = result.get(card,0) + value
        result[card] = total


>>> print result.items()
[('Visa': 1195.5), ('Rogers': 61.5)]

答案 1 :(得分:3)

看起来每个人都忘记了collections.Counter

from collections import Counter


c = Counter()
for card, val in lst:
    c.update({card: val})    
print(list(c.items()))

# [('Visa', 1195.5), ('Rogers', 61.5)]

答案 2 :(得分:3)

collections.defaultdict是最有效的方式:

from collections import defaultdict

l= [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]

d = defaultdict(float)
for k,v in l:
    d[k] += v

输出:

defaultdict(<class 'float'>, {'Visa': 1195.5, 'Rogers': 61.5})

答案 3 :(得分:1)

data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
sum = {}
for item in data:
    if not item[0] in sum:
          sum[ item[0] ] = 0
    sum[ item[0] ] += item[1]
print sum.items()

答案 4 :(得分:0)

如果你想保持列表的顺序,那么我建议使用字典。

lst = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]

lst2 = [(tup[0], sum([val for n, val in lst if n == tup[0]])) for tup in lst]

res = []
for tup in lst2:
    if tup not in res:
        res.append(tup)

print(res)

答案 5 :(得分:0)

使用set:

li=[('Rogers', 10), ('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
s=set([i[0] for i in li])

x=[]
for i in s:
    sum=0
    for j in li:    
        if i == j[0]:
            sum+=j[1]
    x.append(sum)

final_list=zip(s,x)
print final_list

<强>输出:

[('Visa', 1195.5), ('Rogers', 61.5)]