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.
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_value
s, 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))
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