简体   繁体   中英

Find those tuples in which the second element is maximum among all values with same first element

How to sanitize a given list of tuples, such that only tuples with maximum values are listed.

mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]

Result

[('a',6), ('b', 10), ('c', 8), ('d', 12)]

Turn it into a dictionary:

mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]
d = {}

for key, value in mytup:
    if d.get(key) < value:  # d.get(key) returns None if the key doesn't exist
        d[key] = value      # None < float('-inf'), so it'll work

result = d.items()

I think this should work:

dict = {}
for key, val in mytup:
    try:
        if dict[key] < val:
            dict[key] = val
    except IndexError:
        dict[key] = val

Itertools is your friend, one line solution:

from itertools import groupby
print [ max(g) for _, g in groupby(sorted(mytup), lambda x: x[0] )]

Results:

[('a', 6), ('b', 10), ('c', 8), ('d', 12)]

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