Compare values in each element of a list

A question:
I have this list:

list_1=[(‘bg’, 0, 9), (‘bg’, 0, 8), (‘bg’, 1, 5), (‘us’, 0, 5), (‘us’, 0, 2), (‘us’, 1, 6)]

I need to sum each third value of the elements of this list, if the first and the second ones matches.
So, I need to print out this result:

list_2=[(‘bg’,0,17), (‘bg’,1,5), (‘us’,0,7), (‘us’,1,6)]

It should be easy, but I just miss it somehow. Any help?

One way is to use itertools.groupby to create an iterator that groups sequences. The list needs to be pre-sorted first. The function compares elements of one sequence with the next using a key: lambda i: (i[0], i[1]).

Then you just have to concatenate the third element summed.

from itertools import groupby
sorted_1 = sorted(list_1)

grouped = (list(group) for key, group in groupby(sorted_1, lambda i: (i[0], i[1])))
summed = [group[0][:2] + (sum(k for _, _, k in group),) for group in grouped]
1 Like

Cool, thanks!