From a list of tuples, I want to identify the tuples, which hav the maximum value for tuple[2] (i.e. the third value), but the same values otherwise
i.e. from
searchlist = [(a,b,2),(a,b,3),(a,b,4),(a,b,5),(x,y,2),(x,y,4)]
I want to find
result = [(a,b,5),(x,y,4)]
You might first sort your values, then you will be able to use groupby()
to group values with the same two first elements. Finally, max()
can retrieve the maximum value for each.
from itertools import groupby
a, b, x, y = "a", "b", "x", "y"
searchlist = [(a,b,2),(a,b,3),(a,b,4),(a,b,5),(x,y,2),(x,y,4)]
searchlist.sort()
grouped = groupby(searchlist, key=lambda v: (v[0], v[1]))
maximums = [max(groups) for value, groups in grouped]
print(maximums)
# [("a", "b", 5), ("x", "y", 4)]