python - 选择指定位置具有最高整数值的子列表

标签 python max nested-lists

我有一个嵌套列表:

nested_list = [['a', 3], ['a', 1], ['a', 5]]

如何遍历此列表,选择具有最大整数值的子列表?

holder = []

for entry in nested_list:
    tmp = sublist with max entry[2] value
    holder.append(tmp)

我坚持编写第二行代码。

最佳答案

尝试:

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

import operator

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

如果第一项总是'a',你可以这样做

max(nested_list)

如果您愿意深入研究一些类型检查,并且想对任意子列表(仅一个级别。类似于 [12, 'a', 12, 42, 'b'])执行此操作,您可以做类似的事情。

import numbers

max(nested_list, key=lambda x: max(i for i in x 
                                   if isinstance(i, numbers.Integral)))

无论如何,如果您不确定 nested_list 的元素实际上是列表,您可以这样做

import collections

max((s for s in nested_list 
     if isinstance(s, collections.Sequence)), 
    key=some_key_function)

然后将它传递给您自己设计的关键功能或此答案中的其他功能之一。

lambda x: x[1]operator.itemgetter(1) 问题而言,我会进行分析。原则上,itemgetter 应该是一种正确的方法,但我已经看到 operator 解决方案的性能优于 lambda 函数对“错误”的处理(我松散地使用该术语,代码仍然有效)在 operator 中。如果性能无关紧要(可能也是如此),我更喜欢 itemgetter,但有些人喜欢避免额外的 import

关于python - 选择指定位置具有最高整数值的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4299422/

相关文章:

Python Regex 只匹配每个单词大写的地方

python - 如何从多个列表中找到最大值?

python - 列表列表更改意外地反射(reflect)在子列表中

python - 实体组、ReferenceProperty 或键作为字符串

python - matplotlib.pyplot 问题 python

matlab - 在 MATLAB 中查找矩阵子集的最大值,同时保留完整矩阵的索引

python - 如何将嵌套列表作为 Python 中的输入

python - 将未知大小列表的列表拆分为 n 号的数据框。列数

python - Bokeh :使用悬停工具显示图像

c++ - Max 和 Min 显示为 true 而不是数字,我该怎么办?