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