Select sub-list with highest integer value in a specified position

╄→гoц情女王★ 提交于 2019-12-08 08:17:48

问题


I have a nested list:

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.


回答1:


try:

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

or

import operator

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

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

max(nested_list)

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)))

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.

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.




回答2:


Does this do what you want?

biggest = nested_list[0]

for entry in nested_list:
    if entry[1] > biggest[1]:
        biggest = entry



回答3:


If the list is as simple as you suggest:

>>> nested_list = [['a', 3], ['a', 1], ['a', 5], ['a',2]]
>>> k = sorted(nested_list)
>>> k[-1]
['a', 5]
>>> 


来源:https://stackoverflow.com/questions/4299422/select-sub-list-with-highest-integer-value-in-a-specified-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!