Sum numbers by letter in list of tuples

前端 未结 8 1582
不思量自难忘°
不思量自难忘° 2020-12-11 09:44

I have a list of tuples:

[ (\'A\',100), (\'B\',50), (\'A\',50), (\'B\',20), (\'C\',10) ]

I am trying to sum up all numbers that have the s

相关标签:
8条回答
  • 2020-12-11 10:14
    >>> from collections import Counter
    >>> c = Counter()
    >>> for k, num in items:
            c[k] += num
    
    
    >>> c.items()
    [('A', 150), ('C', 10), ('B', 70)]
    

    Less efficient (but nicer looking) one liner version:

    >>> Counter(k for k, num in items for i in range(num)).items()
    [('A', 150), ('C', 10), ('B', 70)]
    
    0 讨论(0)
  • 2020-12-11 10:15

    In order to achieve this, firstly create a dictionary to store your values. Then convert the dict object to tuple list using .items() Below is the sample code on how to achieve this:

    my_list = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
    my_dict = {}
    for key, val in my_list:
        if key in my_dict:
            my_dict[key] += val
        else:
            my_dict[key] = val
    
    my_dict.items()
    # Output: [('A', 150), ('C', 10), ('B', 70)]
    
    0 讨论(0)
提交回复
热议问题