'How to find the index of n largest elements in a list or np.array, Python

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]

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



Solution 1:[1]

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,

 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 :)

Solution 2:[2]

This should work:

K = [1,2,2,4,5,5,6,10]
num = 5
print 'K %s.' % (sorted(K, reverse=True)[:num])

Solution 3:[3]

import headq

Then use function nlargest()

Solution 4:[4]

For efficiency, numpy partition is much more efficient for large array. There is no need to sort fully.

"All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 cforbish
Solution 3 Dhawal Kapil
Solution 4 cosine