Sum numbers by letter in list of tuples

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

    How about this: (assuming a is the name of the tuple you have provided)

    letters_to_numbers = {}
    for i in a:
        if i[0] in letters_to_numbers:
            letters_to_numbers[i[0]] += i[1]
        else:
            letters_to_numbers[i[0]] = i[1]
    b = letters_to_numbers.items()
    

    The elements of the resulting tuple b will be in no particular order.

提交回复
热议问题