Optimal method to find the max of sublist items within list

后端 未结 3 1262
感动是毒
感动是毒 2020-12-21 01:55

I have a multidimensional list in the format:

list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]

How do I obtain the maximum value of the third value

相关标签:
3条回答
  • 2020-12-21 02:28

    Just use max with a generator expression:

    >>> lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]
    >>> max(l[2] for l in lst)
    3
    

    Also, don't name your variables list, you are shadowing the type.

    0 讨论(0)
  • 2020-12-21 02:32

    applying max on the list will return the maximum list, which isn't what you want. You could indeed use a list comprehension to extract the third element, and then apply max on that comprehension:

    >>> lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]
    >>> max([x[2] for x in lst])
    3
    
    0 讨论(0)
  • 2020-12-21 02:49

    Use zip function to get the list of columns then use a simple indexing in order to get the expected column:

    >>> lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]]
    >>> 
    >>> max(zip(*lst)[-1]) # in python 3.x max(list(zip(*lst))[-1])
    3
    

    One another alternative and more pythonic approach is passing a key function to max to get the max item based on the key function. In this case you can use itemgetter(-1) in order to get the max item based on intended index then since the max() function returns the whole item from your list (sub-list) you can get the expected item by indexing:

    >>> from operator import itemgetter
    >>> max(lst, key=itemgetter(-1))[-1]
    3
    

    Or more functional:

    >>> key_func = itemgetter(-1)
    >>> key_func(max(lst, key=key_func))
    3 
    
    0 讨论(0)
提交回复
热议问题