如何找到的n个最大元素以列表或np.array,Python的索引 [英] How to find the index of n largest elements in a list or np.array, Python
本文介绍了如何找到的n个最大元素以列表或np.array,Python的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个内置的功能或发现的n个最大元素列表中的索引或numpy的数组的一个非常简单的方法?
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?
K = [1,2,2,4,5,5,6,10]
找到最大的5个元素的索引?
Find the index of the largest 5 elements?
我算重复多次,输出应该是那些数量最多的指数
I count the duplicates more than once, and the output should be a list of the indices of those largest numbers
推荐答案
也许是这样的:
>>> 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])
这篇关于如何找到的n个最大元素以列表或np.array,Python的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文