Python 在嵌套列表的第二列中查找最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4800419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:35:03  来源:igfitidea点击:

Finding max value in the second column of a nested list?

pythonlistnestedelementmax

提问by davelupt

I have a list like this:

我有一个这样的清单:

alkaline_earth_values = [['beryllium', 4], ['magnesium', 12],['calcium', 20],
                         ['strontium', 38], ['barium', 56], ['radium', 88]]

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(list)方法,它将返回 answer 'strontium',如果我试图找到 max name,这将是正确的,但是我试图返回整数最高的元素。

采纳答案by kynnysmatto

max(alkaline_earth_values, key=lambda x: x[1])

The reason this works is because the keyargument of the maxfunction specifies a function that is called when maxwants to know the value by which the maximum element will be searched. maxwill 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

这样做的原因是因为max函数的key参数指定了一个函数,当max想知道将搜索最大元素的值时调用该函数。max将为序列中的每个元素调用该函数。并创建一个小函数,它接受一个列表并返回第一个(从零开始计数)元素。所以lambda x: x[1]

k = lambda x: x[1]

is the same as saying

和说一样

def k(l):
  return l[1]

but shorter and nice to use in situations like this.

但在这种情况下使用更短而且很好用。

回答by Ignacio Vazquez-Abrams

Use the keyargument.

使用key参数。

max(alk..., key=operator.itemgetter(1))

回答by uytda

it is rather tricky to assume that an item in a list is actually still a number. If the numbers have become strings, the max()will return the 'value' with the highest first number:

假设列表中的项目实际上仍然是一个数字是相当棘手的。如果数字已成为字符串,max()则将返回具有最高第一个数字的“值”:

alkaline_earth_values = [['beryllium', '9'], ['magnesium', '12'],['calcium', '20'],
                         ['strontium', '38'], ['barium', '56'], ['radium', '88']]
max(alkaline_earth_values, key=lambda x: x[1])

returns ['beryllium', '9']

回报 ['beryllium', '9']

max(alkaline_earth_values, key=lambda x: float(x[1]))

will do the trick, when you are sure it will be a number

会做的伎俩,当你确定这将是一个数字

回答by Peter M?lgaard Pallesen

For high speed consider pandas or numpy:

对于高速,请考虑 pandas 或 numpy:

Import pandas as pd
alkaline_earth_values = [['beryllium', 4], ['magnesium', 12],['calcium', 20],
                     ['strontium', 38], ['barium', 56], ['radium', 88]]
pd.DataFrame(alkaline_earth_values)[1].max()