开发者

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

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开发者_Python百科.


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.


Does this do what you want?

biggest = nested_list[0]

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


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]
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜