简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM