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 of all the sublists. In pseudo code:
max(list[0][2], list[1][2], list[2][2])
I know this can be done via iterating over the list and extracting the third value into a new list, then simply performing max(list)
, but I'm wondering if this can be done using a lambda or list comprehension?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With