Sum numbers by letter in list of tuples

前端 未结 8 1589
不思量自难忘°
不思量自难忘° 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:01

    What is generating the list of tuples? Is it you? If so, why not try a defaultdict(list) to append the values to the right letter at the time of making the list of tuples. Then you can simply sum them. See example below.

    >>> from collections import defaultdict
    >>> val_store = defaultdict(list)
    >>> # next lines are me simulating the creation of the tuple
    >>> val_store['A'].append(10)
    >>> val_store['B'].append(20)
    >>> val_store['C'].append(30)
    >>> val_store
    defaultdict(, {'C': [30], 'A': [10], 'B': [20]})
    >>> val_store['A'].append(10)
    >>> val_store['C'].append(30)
    >>> val_store['B'].append(20)
    >>> val_store
    defaultdict(, {'C': [30, 30], 'A': [10, 10], 'B': [20, 20]})
    
    >>> for val in val_store:
    ...   print(val, sum(val_store[val]))
    ... 
    C 60
    A 20
    B 40
    

提交回复
热议问题