是否有内置函数或非常简单的方法来查找列表或numpy数组中n个最大元素的索引?
K = [1,2,2,4,5,5,6,10]
找到最大的5个元素的索引?
我不止一次地计算重复项,输出应该是那些最大数字的索引列表
答案 0 :(得分:26)
可能是这样的:
>>> K
[4, 5, 1, 6, 2, 5, 2, 10]
>>> sorted(range(len(K)), key=lambda x: K[x])
[2, 4, 6, 0, 1, 5, 3, 7]
>>> sorted(range(len(K)), key=lambda x: K[x])[-5:]
[0, 1, 5, 3, 7]
或使用numpy
,您可以使用argsort
:
>>> np.argsort(K)[-5:]
array([0, 1, 5, 3, 7])
argsort
也是一种方法:
>>> K = np.array(K)
>>> K.argsort()[-5:]
array([0, 1, 5, 3, 7])
>>> K[K.argsort()[-5:]]
array([ 4, 5, 5, 6, 10])
答案 1 :(得分:3)
考虑以下代码,
N=5
K = [1,10,2,4,5,5,6,2]
#store list in tmp to retrieve index
tmp=list(K)
#sort list so that largest elements are on the far right
K.sort()
#To get the 5 largest elements
print K[-N:]
#To get the 5th largest element
print K[-N]
#get index of the 5th largest element
print tmp.index(K[-N])
如果您想忽略重复项,请按如下所示使用set(),
N=5
K = [1,10,2,4,5,5,6,2]
#store list in tmp to retrieve index
tmp=list(K)
#sort list so that largest elements are on the far right
K.sort()
#Putting the list to a set removes duplicates
K=set(K)
#change K back to list since set does not support indexing
K=list(K)
#To get the 5 largest elements
print K[-N:]
#To get the 5th largest element
print K[-N]
#get index of the 5th largest element
print tmp.index(K[-N])
希望其中一个涵盖您的问题:)
答案 2 :(得分:2)
这应该有效:
K = [1,2,2,4,5,5,6,10]
num = 5
print 'K %s.' % (sorted(K, reverse=True)[:num])
答案 3 :(得分:-2)
import headq
然后使用函数nlargest()