-1

I have a list:

l = [("abc",0.9), ("abc1",0.95), ("abc2",0.8), ("abc3",0.9)]

I want to get the tuple with the highest second tuple value, i.e.

("abc1", 0.95)

What's the best way to achieve this?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
william007
  • 17,375
  • 25
  • 118
  • 194

3 Answers3

3

You'd use the key argument to the max() function:

max(l, key=lambda i: i[1])

You can also use operator.itemgetter() to produce a callable here:

from operator import itemgetter
max(l, key=itemgetter(1))

Demo:

>>> l=[("abc",0.9),("abc1",0.95),("abc2",0.8),("abc3",0.9)]
>>> max(l, key=lambda i: i[1])
('abc1', 0.95)
>>> from operator import itemgetter
>>> max(l, key=itemgetter(1))
('abc1', 0.95)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

You can simply use max function, with the key parameter as a function which can give the second element of each tuple to compare, like this

print max(l, key=lambda x: x[1])
# ('abc1', 0.95)

Otherwise you can use the builtin itemgetter operator, like this

from operator import itemgetter
print max(l, key=itemgetter(1))
# ('abc1', 0.95)
will
  • 10,260
  • 6
  • 46
  • 69
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

Use the key keyword argument in the built-in max function: you can pass it a function which looks at the element at index 1 (i.e. the second element) of the tuple:

>>> max(l, key=lambda x: x[1])
("abc1", 0.95)
Alex Riley
  • 169,130
  • 45
  • 262
  • 238