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

Dar*_*ick 1 python max nested-lists

我有一个嵌套列表:

nested_list = [['a', 3], ['a', 1], ['a', 5]]
Run Code Online (Sandbox Code Playgroud)

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

holder = []

for entry in nested_list:
    tmp = sublist with max entry[2] value
    holder.append(tmp)
Run Code Online (Sandbox Code Playgroud)

我坚持编码第二行.

任何帮助非常感谢.

aar*_*ing 8

尝试:

max(nested_list, key=lambda x: x[1])
Run Code Online (Sandbox Code Playgroud)

要么

import operator

max(nested_list, key=operator.itemgetter(1))
Run Code Online (Sandbox Code Playgroud)

如果第一个项目永远是'a',你可以这样做

max(nested_list)
Run Code Online (Sandbox Code Playgroud)

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

import numbers

max(nested_list, key=lambda x: max(i for i in x 
                                   if isinstance(i, numbers.Integral)))
Run Code Online (Sandbox Code Playgroud)

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

import collections

max((s for s in nested_list 
     if isinstance(s, collections.Sequence)), 
    key=some_key_function)
Run Code Online (Sandbox Code Playgroud)

并且只是传递一个你自己设计的关键功能或其他一个在这个答案中.

在方面lambda x: x[1]operator.itemgetter(1)问题,我的个人资料.在可行的情况下,itemgetter应该是一种正确的方法,但我已经看到operator解决方案的性能优于lambda函数做'错误'(我使用松散的术语,代码仍然有效)operator.我的偏好是因为itemgetter性能无关紧要(并且可能是这样)但有些人喜欢避免额外的import.