qwerty ayyy
qwerty ayyy

Reputation: 385

Comparing a list of tuples

I want to compare a list of tuples, if the first elements are the same then compare the second elements and return the highest.

lis = [(1,10, "n"), (1,15,"n1"), (2,20,"n"),(2,35,"n1"),(3,123,"n"),(3,12,"n1")]

return:

lis = [(1,15,"n1"), (2,35,"n1"), (3,123,"n")]

I'm not sure how to go about this, any help would be appreciated.

Upvotes: 0

Views: 1177

Answers (3)

DeepSpace
DeepSpace

Reputation: 81594

I'd use itertools.groupby to first group all items with the same first element together, then max to find the items with the max second element.

Unlike some other answers you may have varying number of elements from different "groups".

from itertools import groupby
from operator import itemgetter

lis = [(1,10, "n"), (1,15,"n1"), (2,20,"n"), (2,35,"n1"), (3,123,"n"),(3,12,"n1")]

lis.sort(key=itemgetter(0))  # groupby requires the iterable to be sorted,
                             # so making sure it is

grouped_by = groupby(lis, key=itemgetter(0))

output = [max(li, key=itemgetter(1)) for group, li in grouped_by]
print(output)

# [(1, 15, 'n1'), (2, 35, 'n1'), (3, 123, 'n')]

Upvotes: 3

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

Tuple comparisons do that already, comparing first elements then second and continuing until a tie-breaker is found.

All you need to do is zip the list in such a way to create the correct comparisons:

zip(lis[::2], lis[1::2])
# This produces:
# (1, 10, 'n') (1, 15, 'n1')
# (2, 20, 'n') (2, 35, 'n1')
# (3, 123, 'n') (3, 12, 'n1')

Creates the pairs you need, you can then compare them inside a list-comprehension to get the wanted results:

r = [i if i > j else j for i,j in zip(lis[::2], lis[1::2])]
print(r)
# [(1, 15, 'n1'), (2, 35, 'n1'), (3, 123, 'n')]

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using range() and max() functions:

lis = [(1,10, "n"), (1,15,"n1"), (2,20,"n"),(2,35,"n1"),(3,123,"n"),(3,12,"n1")]
result = [max(lis[i:i+2]) for i in range(0, len(lis), 2)]

print(result)

The output:

[(1, 15, 'n1'), (2, 35, 'n1'), (3, 123, 'n')]

Upvotes: 1

Related Questions