名称相同的列表中的总和

2024-04-19 22:14:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个这样的列表

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

我怎样才能得到总金额的货币如下?在

^{pr2}$

Tags: 列表货币usdmylistpr2总金额thb
2条回答

如果您想将同一种货币的价值相加,这有助于:

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

相关问题 更多 >