Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal method to find the max of sublist items within list

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?

like image 514
ugotchi Avatar asked Dec 15 '22 04:12

ugotchi


2 Answers

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.

like image 175
tobias_k Avatar answered Jan 05 '23 00:01

tobias_k


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 
like image 44
Mazdak Avatar answered Jan 04 '23 22:01

Mazdak