Reputation: 4531
So I have a list of tuples which I created from zipping two lists like this:
zipped =list(zip(neighbors, cv_scores))
max(zipped)
produces
(49, 0.63941769316909292)
where 49 is the max value.
However, I'm interesting in finding the max value among the latter value of the tuple (the .63941).
How can I do that?
Upvotes: 1
Views: 2514
Reputation: 477685
The problem is that Python compares tuples lexicographically so it orders on the first item and only if these are equivalent, it compares the second and so on.
You can however use the key=
in the max(..)
function, to compare on the second element:
max(zipped,key=lambda x:x[1])
Note 1: Note that you do not have to construct a
list(..)
if you are only interested in the maximum value. You can usemax(zip(neighbors,cv_scores),key=lambda x:x[1])
.Note 2: Finding the
max(..)
runs in O(n) (linear time) whereas sorting a list runs in O(n log n).
Upvotes: 3
Reputation: 6758
max(zipped)[1]
#returns second element of the tuple
This should solve your problem in case you want to sort your data
and find the maximum you can use itemgetter
from operator import itemgetter
zipped.sort(key=itemgetter(1), reverse = True)
print(zipped[0][1]) #for maximum
Upvotes: 1