How to sum values of tuples that have same name in Python -


i have following list containing tuples have values:

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

is there way sum values share same name? like:

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

i tried iterating tuples loop can't want.

thank you

you can use itertools.groupby (after sorting second value of each tuple) create groups. each group, sum first element in each tuple, create tuple per group in list comprehension.

>>> import itertools >>> [(sum(i[0] in group), key) key, group in itertools.groupby(sorted(mylist, key = lambda i: i[1]), lambda i: i[1])] [(9, 'a'), (3, 'b'), (5, 'c')] 

Comments