How to sum values of tuples that have same name in

2020-01-29 18:01发布

问题:

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

回答1:

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')]


回答2:

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')]


回答3:

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


回答4:

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')]