选择在指定位置具有最大整数值的子列表 [英] Select sub-list with highest integer value in a specified position

查看:52
本文介绍了选择在指定位置具有最大整数值的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套列表:

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

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

How do I iterate over this list, select the sublist with the max integer value?

holder = []

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

我被困在第二行编码上.

I am stuck on coding the second line.

推荐答案

尝试:

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

import operator

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

如果第一项始终为'a',您可以这样做

If the first item will always be 'a', you can just do

max(nested_list)

如果您愿意深入进行类型检查,并且想要对任意子列表(仅在一个级别,例如[12,'a',12,12,42,'b']之类)进行此操作,则可以做类似的事情.

If you're willing to dive into some type checking and you want to do this for arbitrary sublists (Of one level only. something like [12, 'a', 12, 42, 'b']), you can do something like.

import numbers

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

无论如何,如果您不确定nested_list的元素是否确实在列表中,则可以

In any case, if you're not sure that the elements of nested_list are in fact lists, you can do

import collections

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

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

and just pass it a key function of your own devising or one of the other ones in this answer.

关于lambda x: x[1] vs. operator.itemgetter(1)问题,我将介绍一下.在切实可行的情况下,itemgetter应该是正确的方法,但我已经看到operator解决方案的性能优于lambda函数对operator中的错误"(我使用的术语是宽松的,代码仍然有效).如果性能无关紧要(可能的话),我更喜欢itemgetter,但是有些人希望避免使用多余的import.

In terms of the lambda x: x[1] vs. operator.itemgetter(1) question, I would profile. In princible, itemgetter should be the one right way but I've seen operator solutions get outperformed by lambda function do to 'bugs' (I use the term loosely, the code still works) in operator. My preference would be for itemgetter if performance doesn't matter (and probably if it does) but some people like to avoid the extra import.

这篇关于选择在指定位置具有最大整数值的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆