如何在列表或 np.array 中找到 n 个最大元素的索引,Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16878715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the index of n largest elements in a list or np.array, Python
提问by Logan Yang
Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?
是否有内置函数或一种非常简单的方法来查找列表或 numpy 数组中 n 个最大元素的索引?
K = [1,2,2,4,5,5,6,10]
Find the index of the largest 5 elements?
找到最大的 5 个元素的索引?
I count the duplicates more than once, and the output should be a list of the indices of those largest numbers
我不止一次计算重复项,输出应该是那些最大数字的索引列表
采纳答案by DSM
Maybe something like:
也许是这样的:
>>> 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]
or using numpy, you can use argsort:
或使用numpy,您可以使用argsort:
>>> np.argsort(K)[-5:]
array([0, 1, 5, 3, 7])
argsortis also a method:
argsort也是一种方法:
>>> K = np.array(K)
>>> K.argsort()[-5:]
array([0, 1, 5, 3, 7])
>>> K[K.argsort()[-5:]]
array([ 4, 5, 5, 6, 10])
回答by Curious
Consider the following code,
考虑以下代码,
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])
If you wish to ignore duplicates, then use set() as follows,
如果您希望忽略重复项,请按如下方式使用 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])
Hopefully one of them covers your question :)
希望其中之一涵盖了您的问题:)
回答by cforbish
This should work:
这应该有效:
K = [1,2,2,4,5,5,6,10]
num = 5
print 'K %s.' % (sorted(K, reverse=True)[:num])

