简体   繁体   English

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

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

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

max(alkaline_earth_values, key=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函数的key参数指定了一个函数,当max想知道将搜索最大元素的值时调用该函数。 max will call that function for each element in the sequence. max将为序列中的每个元素调用该函数。 And lambda x: x[1] creates a small function which takes in a list and returns the first (counting starts from zero) element.并且lambda x: x[1]创建一个小函数,它接受一个列表并返回第一个(从零开始计数)元素。 So所以

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.但在这种情况下使用更短而且很好用。

使用key参数。

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

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会做的伎俩,当你确定这将是一个数字

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()

You could convert your list of lists to a Counter and the call the .most_common() method.您可以将列表列表转换为Counter并调用.most_common()方法。 This easily allow you to find the maximum or top n values:这很容易让您找到最大值或前 n 个值:

>>> from collections import Counter
>>> Counter(dict(alkaline_earth_values)).most_common(1)
[('radium', 88)]
>>> Counter(dict(alkaline_earth_values)).most_common(3)
[('radium', 88), ('barium', 56), ('strontium', 38)]

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

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