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?
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?
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)
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)
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)