【问题标题】:Sum in list with the same name [closed]在具有相同名称的列表中求和[关闭]
【发布时间】:2015-03-04 04:56:28
【问题描述】:

鉴于[(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’
>>>

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

【问题讨论】:

  • 你的预期输出是什么?

标签: python list sum


【解决方案1】:

以防万一您想总结相同货币的价值,这会有所帮助:

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

【讨论】:

    【解决方案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])) 
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2020-06-25
      • 1970-01-01
      • 2014-10-16
      相关资源
      最近更新 更多