How to sum values of tuples that have same name in

2020-01-29 17:37发布

I have the following list containing tuples that have to values:

mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')]

Is there a way to sum all values that share the same name? Something like:

(9, 'a'), (3, 'b'), (5, 'c')

I tried iterating tuples with for loop but can't get what i want.

Thank you

4条回答
做自己的国王
2楼-- · 2020-01-29 18:07

You can use itertools.groupby (after sorting by the second value of each tuple) to create groups. Then for each group, sum the first element in each tuple, then create a tuple per group in a list comprehension.

>>> import itertools
>>> [(sum(i[0] for i in group), key) for key, group in itertools.groupby(sorted(mylist, key = lambda i: i[1]), lambda i: i[1])]
[(9, 'a'), (3, 'b'), (5, 'c')]
查看更多
▲ chillily
3楼-- · 2020-01-29 18:13

A simple approach without any dependencies:

mylist = [(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')]

sums = {}
for a, b in mylist:
    if b not in sums: sums[b] = a
    else: sums[b] += a

print list(sums.items())
查看更多
可以哭但决不认输i
4楼-- · 2020-01-29 18:23

Use a dict (or defaultdict) to aggregate over your tuples:

from collections import defaultdict
mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')]
sums = defaultdict(int)
for i, k in mylist:
    sums[k] += i   

print sums.items()
# output: [('a', 9), ('c', 5), ('b', 3)]

# Or if you want the key/value order reversed and sorted by key
print [(v, k) for (k, v) in sorted(sums.items())]
# output: [(9, 'a'), (3, 'b'), (5, 'c')]
查看更多
劳资没心,怎么记你
5楼-- · 2020-01-29 18:23

You can create a dict which has sum of individual keys.

>>> my_dict = {}
>>> for item in mylist:
...     my_dict[item[1]] = my_dict.get(item[1], 0) + item[0]
>>> [(my_dict[k], k) for k in my_dict]
[(9, 'a'), (5, 'c'), (3, 'b')]
查看更多
登录 后发表回答