在Python中实现argmax

26 投票
5 回答
20836 浏览
提问于 2025-04-16 12:25

5 个回答

8
def argmax(lst):
     return lst.index(max(lst))
argmax = lambda lst: lst.index(max(lst)

或者可以这样理解:

21

下面的代码是一种快速且符合Python风格的方法吗?

idx_max = max(enumerate(x), key=lambda x:x[1])[0]
31

我对我找到的最佳解决方案进行了修改:

# given an iterable of pairs return the key corresponding to the greatest value
def argmax(pairs):
    return max(pairs, key=lambda x: x[1])[0]

# given an iterable of values return the index of the greatest value
def argmax_index(values):
    return argmax(enumerate(values))

# given an iterable of keys and a function f, return the key with largest f(key)
def argmax_f(keys, f):
    return max(keys, key=f)

撰写回答