在列表中使用相同的名称求和

时间:2015-03-04 04:56:29

标签: python list sum

我在python中有这样的列表

mylist=[('USD',1000),('THB',25),('USD',3500)]

我如何获得如下所示的货币总额?

[('USD', 4500), ('THB', 25)]

2 个答案:

答案 0 :(得分:3)

如果您想总结相同货币的价值,这可以提供帮助:

from collections import defaultdict

my_dict = defaultdict(int)

for k,v in mylist:
    my_dict[k] += v

print(my_dict)   
# defaultdict(<class 'int'>, {'USD': 4500, 'THB': 25})

答案 1 :(得分:2)

mylist=[('USD',1000),('THB',25),('USD',3500)]

# Initialise the aggregator dictionary
res = {}

# Populate the aggregator dictionary
for cur, val in mylist:
    if cur in res:
        # If the currency already exists, add the value to its total
        res[cur] += val
    else:
        # else create a new key/value pair in the dictionary.
        res[cur] = val

# And some nice output
for key in res:
    print('{:>5}: {:>6}'.format(key, res[key]))