简体   繁体   English

查找元组列表的最大值,(将max应用于元组的第二个值)

[英]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. max(zipped)产生(49, 0.63941769316909292) ,其中49是最大值。

However, I'm interesting in finding the max value among the latter value of the tuple (the .63941). 但是,我很有兴趣在元组的后一个值中找到最大值(.63941)。

How can I do that? 我怎样才能做到这一点?

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. 问题是Python按字典顺序比较元组,因此它在第一个项目上进行排序 ,并且只有在它们相同的情况下,它才比较第二个项目,依此类推。

You can however use the key= in the max(..) function, to compare on the second element: 但是,您可以在max(..)函数中使用key=比较第二个元素:

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 . 注1 :请注意, 如果您只对最大值感兴趣,则不必构造list(..) You can use max(zip(neighbors,cv_scores),key=lambda x:x[1]) . 你可以使用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) . 注2 :查找max(..)O(n) (线性时间)中运行,而排序列表在O(n log n)中运行

max(zipped)[1] #returns second element of the tuple 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 这可以解决您的问题,以防您想要对数据进行排序并找到可以使用itemgetter的最大值

from operator import itemgetter
zipped.sort(key=itemgetter(1), reverse = True)
print(zipped[0][1]) #for maximum 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM