我正在尝试找到一个函数,它返回给定列表中所有出现的最大值.
numpy.argmax但是只返回它找到的第一个匹配项.例如:
from numpy import argmax
list = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6]
winner = argmax(list)
print winner
Run Code Online (Sandbox Code Playgroud)
只给出索引0.但我希望它能给出所有指数:0, 3, 5.
jab*_*edo 68
正如文档所述np.argmax:"如果多次出现最大值,则返回与第一次出现相对应的索引." ,所以你需要另一个策略.
您有一个选择是np.argwhere结合使用np.amax:
>>> import numpy as np
>>> listy = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6]
>>> winner = np.argwhere(listy == np.amax(listy))
>>> print(winner)
[[0]
[3]
[5]]
>>> print(winner.flatten().tolist()) # if you want it as a list
[0, 3, 5]
Run Code Online (Sandbox Code Playgroud)
Lig*_*ark 17
与其他答案相比,如果您使用np.flatnonzero:
>>> import numpy as np
>>> your_list = np.asarray([7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6])
>>> winners = np.flatnonzero(your_list == np.max(your_list))
>>> winners
array([0, 3, 5])
Run Code Online (Sandbox Code Playgroud)
如果你想要一个列表:
>>> winners.tolist()
[0, 3, 5]
Run Code Online (Sandbox Code Playgroud)
万一重要,以下算法以 O(n) 而不是 O(2n) 运行(即,使用np.argmax然后np.argwhere):
def allmax(a):
if len(a) == 0:
return []
all_ = [0]
max_ = a[0]
for i in range(1, len(a)):
if a[i] > max_:
all_ = [i]
max_ = a[i]
elif a[i] == max_:
all_.append(i)
return all_
Run Code Online (Sandbox Code Playgroud)