Moondra
Moondra

Reputation: 4531

Finding the max value of a list of tuples, (applying max to the second value of the tuple)

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

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

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 use max(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

Equinox
Equinox

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

Related Questions