user2578185
user2578185

Reputation: 437

Find the top value from a list of tuples

If I have this list of tuples:

[('123c', 0.0), ('123c1', 0.0), ('123c2', 0.10456917162915072), ('123c3', 0.097595441008939465), ('123c4', 0.0), ('12c35', 0.0), ('13836', 0.040490933063262943)]

How can I find the top value in the whole list, and return the first element in the tuple it belongs?

For the example above, the result would be: '123c2' because 0.10456917162915072 is the top value

Thanks

Upvotes: 0

Views: 68

Answers (2)

Sukrit Kalra
Sukrit Kalra

Reputation: 34513

Something like this?

>>> a = [('123c', 0.0), ('123c1', 0.0), ('123c2', 0.10456917162915072), ('123c3', 0.097595441008939465), ('123c4', 0.0), ('12c35', 0.0), ('13836', 0.040490933063262943)]
>>> max(a, key = lambda x: x[1]) # Or max(a, key = itemgetter(1))
('123c2', 0.10456917162915072)
>>> max(a, key = lambda x: x[1])[0]
'123c2'

About the max() function,

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

The second argument to max(...) in the above example is the key function which lets the function decide which value to maximise.

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1123360

You are looking for the maximum; the max() function does that for you, and you can supply it with a function to determine what value the maximum is determined by:

from operator import itemgetter

max(inputlist, key=itemgetter(1))[0]

Here, operator.itemgetter() provides that function; it takes the specified element from any object you pass to it.

Demo:

>>> inputlist = [('123c', 0.0), ('123c1', 0.0), ('123c2', 0.10456917162915072), ('123c3', 0.097595441008939465), ('123c4', 0.0), ('12c35', 0.0), ('13836', 0.040490933063262943)]
>>> from operator import itemgetter
>>> max(inputlist, key=itemgetter(1))[0]
'123c2'

Upvotes: 1

Related Questions