问题描述
我有一个这样的列表:
alkaline_earth_values = [['beryllium', 4],
['magnesium', 12],
['calcium', 20],
['strontium', 38],
['barium', 56],
['radium', 88]]
如果我简单地使用 max(list)
方法,它会返回答案 'strontium'
,如果我试图找到最大值 name,但是我试图返回整数最高的元素.
If I simply use the max(list)
method, it will return the answer 'strontium'
, which would be correct if I was trying to find the max name, however I'm trying to return the element whose integer is highest.
推荐答案
max(alkaline_earth_values, key=lambda x: x[1])
这样做的原因是因为 max 函数的 key 参数指定了当 max 想要知道值时调用的函数将搜索的最大元素.max 将为序列中的每个元素调用该函数.lambda x: x[1]
创建一个小函数,它接受一个列表并返回第一个(从零开始计数)元素.所以
The reason this works is because the key argument of the max function specifies a function that is called when max wants to know the value by which the maximum element will be searched. max will call that function for each element in the sequence. And lambda x: x[1]
creates a small function which takes in a list and returns the first (counting starts from zero) element. So
k = lambda x: x[1]
和说的一样
def k(l):
return l[1]
但在这种情况下使用更短而且很好用.
but shorter and nice to use in situations like this.
这篇关于在嵌套列表的第二列中查找最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!