Skip to main content
 首页 » 编程设计

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

2025年05月04日9Leo_wl

我有一个嵌套列表:

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。