同名列表求和

Sum in list with the same name

鉴于 [(Currency1, amount1),(Currency2, amount2)] 格式的 turple 列表,我想按主要货币对每个金额求和,但它不起作用。我试过了:

    >>> mylist=[(‘USD’,1000),(‘THB’,25),(‘USD’,3500)]
    >>> for i in mylist:
...         sum += i[1]
...
Traceback (most recent call last):
  File “<stdin>“, line 2, in <module>
TypeError: unsupported operand type(s) for +=: ‘builtin_function_or_method’ and ‘int’
>>>

我想知道如何按货币汇总金额,这将 return 作为 turple 列表,如下所示: [(‘USD’, 4500), (‘THB’, 25)] 请帮忙谢谢。

以防万一你想总结相同货币的价值,这可以帮助:

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