在Python中实现argmax

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

在Python中,argmax应该怎么实现呢?它应该尽可能高效,所以要能处理可迭代的对象。

可以有三种实现方式:

  • 给定一组键值对,返回对应最大值的键
  • 给定一组值,返回最大值的索引
  • 给定一组键和一个函数f,返回使得f(key)最大的键

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)

撰写回答