Daniel Poh
Daniel Poh

Reputation: 129

Find smallest Index of max in nested loop, with key strictly in 0th index

When finding the max value in a nested loop at a certain index, the key usually takes priority. If there are multiple max values at the key in the list where the max value takes in, then other elements in the nested list are used to find the index of the max.

Example:

my_list = [[1, 2], [2, 3], [2, 7]]
print(max(my_list))

Output:

[2, 7]

However, I wish to find the smallest index of the maximum value in the 0th index, without any interference from other values in the list, and using optimised code.

Right now, here is what I am doing to achieve my goal, and it does not look like the most efficient way to do so.

my_list = [[1, 2], [2, 3], [2, 7]]
maximum_val = max(my_list)[0]
for item in my_list:
    if item[0] == maximum_val:
        print(my_list.index(item))
        break

Output:

1

Can someone kindly give a more time-optimised form of what my current code does, without importing external libraries?

Upvotes: 1

Views: 127

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124110

You are asking max() to find the biggest list, and [2, 7] is larger than [2, 3], because lists are ordered lexicographically.

Don't compare lists. Use a key function to select the first integer:

max(my_list, key=lambda nested: nested[0])

This returns the element from my_list for which the value returned by the key function is the maximum. In case of multiple elements with the same maximum, the first such element is returned:

>>> my_list = [[1, 2], [2, 3], [2, 7]]
>>> max(my_list, key=lambda nested: nested[0])
[2, 3]

Next, to get the index of that element, pass in indices to max(), and have the key function map those indices to a value to compare:

max(range(len(my_list)), key=lambda idx: my_list[idx][0])

So this takes a sequence of integers from 0 up to (but not including) the length of your my_list list, then uses the key function to return the first integer of the element at that index in the my_list list:

>>> my_list = [[1, 2], [2, 3], [2, 7]]
>>> max(range(len(my_list)), key=lambda idx: my_list[idx][0])
1

Upvotes: 1

Related Questions