Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum value from a list of lists and its index

li = [[1,2], [2,3], [7,6]]

How can I find the max value and its index efficiently? Suppose for li I want:

max_value = 7

max_index = (2, 0)

I can do this as below:

max_value = 0
for row_idx, row in enumerate(alignment_matrix):    
    for col_idx, col in enumerate(row):
        if col > max_value:
            max_value = col
            max_index = (row_idx, col_idx)

But I need an efficient way without using too many unnecessary variables.

like image 725
zaman sakib Avatar asked Aug 02 '15 13:08

zaman sakib


1 Answers

Using max and generator expression, you can express it more shortly:

max_value, max_index = max((x, (i, j))
                           for i, row in enumerate(li)
                           for j, x in enumerate(row))

But, time complexity is same because this one also uses nested loop.

UPDATE

As @jonrsharpe pointed, in the case of duplicate max_values, above solution will give you the largest index at which the value found.

If that's not what you want, you can pass key function argument to max to customize the behavior:

max_value, max_index = max(((x, (i, j))
                            for i, row in enumerate(li)
                            for j, x in enumerate(row)),
                           key=lambda (x, (i, j)): (x, -i, -j))
like image 160
falsetru Avatar answered Sep 21 '22 21:09

falsetru