在Python中实现argmax [英] implementing argmax in Python
本文介绍了在Python中实现argmax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
应如何在Python中实现argmax?它应该尽可能高效,因此应该与可迭代对象一起使用.
How should argmax be implemented in Python? It should be as efficient as possible, so it should work with iterables.
它的三种实现方式:
- 如果有一对可迭代的键,则返回对应于最大值的键
- 给出一个可迭代的值,返回最大值的索引
- 给定键的可迭代项和函数
f
,返回具有最大f(key)
的键
- given an iterable of pairs return the key corresponding to the greatest value
- given an iterable of values return the index of the greatest value
- given an iterable of keys and a function
f
, return the key with largestf(key)
推荐答案
我修改了找到的最佳解决方案:
I modified the best solution I found:
# 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)
这篇关于在Python中实现argmax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文