有没有内置函数或者非常简单的方法来查找列表或numpy数组中n个最大元素的索引?
K = [1,2,2,4,5,5,6,10]
找到最大5个元素的索引?
我会将重复的元素计算多次,并输出这些最大数字的索引列表。
也许可以是这样的:
>>> 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])
import heapq;heapq.nlargest(n, range(len(K)), key=lambda x: K[x])
。 - Makers_F 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])
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])
K = [1,2,2,4,5,5,6,10]
num = 5
print 'K %s.' % (sorted(K, reverse=True)[:num])
np.argpartition(K,-5)[-5:]
返回前五个最大值的 索引,即 [3, 4, 5, 6, 7]。使用这些索引在 K 上,np.array(K)[ np.argpartition(K,-5)[-5:] ]
返回实际的五个最大值,即 [ 4, 5, 5, 6, 10] (你也可以直接使用 np.partition(K,-5)[-5:]
获取这些值)。 - gnoodleimport headq
然后使用函数nlargest()
headq
而不是heapq
。(2)请用完整的英语句子书写。(3)请给出一个使用示例。(4)你还可以链接到文档:https://docs.python.org/3/library/heapq.html#heapq.nlargest - Stef
[1,2,2,4,5,10,5,6,10]
,输出会是什么? - Ashwini Chaudhary