Suppose I want to find the index of the maximal value of a given sequence. In Matlab, this is:
[value, index] = max(x)
In Python, I would abstract the following pattern:
def find_best_element_index(elements, is_better):
best_so_far = elements[0]
best_so_far_index = 0
for (index, element) in enumerate(elements):
if is_better(element, best_so_far):
best_so_far = element
best_so_far_index = index
return best_so_far_index
Which I could use in the following way:
import operator
assert find_best_element_index([6, 3, 9, 8, 0, 9, 7, 9, 7, 8], operator.gt) == 2
But I wonder if there is a more pythonic way to go when I just want to find the index of the "best" item.