在嵌套列表的第二列中查找最大值?
我有一个这样的列表:
alkaline_earth_values = [['beryllium', 4],
['magnesium', 12],
['calcium', 20],
['strontium', 38],
['barium', 56],
['radium', 88]]
如果我简单地使用 max(list)
方法,它将返回答案 'strontium'
,如果我试图这样做,这将是正确的找到最大的名称,但是我试图返回整数最大的元素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这样做的原因是因为 max 函数的 key 参数指定了一个函数,当 max 想知道该值时调用该函数。将搜索最大元素。 max 将为序列中的每个元素调用该函数。 lambda x: x[1] 创建一个小函数,它接受一个列表并返回第一个(从零开始计数)元素。 So
与 said 相同,
但更短并且在这种情况下使用起来很好。
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. Sois the same as saying
but shorter and nice to use in situations like this.
使用
key
参数。Use the
key
argument.假设列表中的项目实际上仍然是数字是相当棘手的。如果数字已变成字符串,则
max()
将返回第一个数字最大的“值”:returns
['beryllium', '9']
将执行以下操作技巧,当你确定它是一个数字时
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:returns
['beryllium', '9']
will do the trick, when you are sure it will be a number
对于高速,请考虑 pandas 或 numpy:
For high speed consider pandas or numpy:
您可以将列表列表转换为
Counter
并调用.most_common()
方法。这可以让您轻松找到最大或前 n 个值:You could convert your list of lists to a
Counter
and the call the.most_common()
method. This easily allow you to find the maximum or top n values: