Get the pair with max value from list in a list

Viewed 69

I have a list l1 that contains multiple lists that contains a letter with a number. For each letter I want to get the pair with the highest number.

l1 = [['A', 4.54], ['A', 1.23], ['B', 1.23], ['A', 9.23], ['B', 6.23], ['C', 10.55]]

this is what I would like to get:

l2 =[['A', 9.23], ['B', 6.23], ['C', 10.55]]

I can't seem to solve this. Any suggestions ?

3 Answers

Just use a dict to group the results:

>>> result = {}
>>> for letter, number in l1:
...     result[letter] = max(number, result.get(letter, number))
...
>>> result
{'A': 9.23, 'B': 6.23, 'C': 10.55}

If you must have a list, use:

>>> list(result.items())
[('A', 9.23), ('B', 6.23), ('C', 10.55)]

Native python:

l1 = [['A', 4.54], ['A', 1.23], ['B', 1.23], ['A', 9.23], ['B', 6.23], ['C', 10.55], ['C', 3.0]]

nl = sorted(l1)
result = list(dict(nl).items())


print(result)

You could do this with itertools as well, sort the list first by letter, then get the max of each group.

from itertools import groupby

l1 = [['A', 4.54], ['A', 1.23], ['B', 1.23], ['A', 9.23], ['B', 6.23], ['C', 10.55]]

l1 = sorted(l1, key=lambda x: x[0])
result = [max(v, key=lambda x: x[1]) for _, v in groupby(l1, key=lambda x: x[0])]
print(result)
Related