Home > Back-end >  Get indices of top N values from list in the order of the values
Get indices of top N values from list in the order of the values

Time:09-09

I have a list like a=[3,5,7,12,4,1,5] and need to get the indices of the top K(=3) elements of this list, in the order of the elements. So in this case, result should be

[3,2,0]

since top 3 elements are 12, 7, 5 (last one is tie so first index is returned).

What is the simplest way to get this?

CodePudding user response:

I assume you mean 3,2,1 right?

[a.index(i) for i in sorted(a)[:3:-1]]

CodePudding user response:

As this is tagged , you can use numpy.argsort on the opposite values (for reverse sorting), then slice to get the K desired values:

a = np.array([3,5,7,12,4,18,1,5,18])
K = 3
out = np.argsort(-a)[:K]

output: array([3, 2, 1])

If you want the indices in order of the original array but not necessarily sorted themselves in order of the values, you can also use numpy.argpartition:

out = np.argpartition(a, K)[-K:]

CodePudding user response:

Personally, I would create a sorted list through the sorted method, then compare the first K values with the .index attribute of a. This will yield you your desired result.

K = 3 #Number of elemens

a = [3,5,7,12,4,1,5]

a_sorted = sorted(a,reverse=True)

b = [a.index(v) for v in a_sorted[:K]]
print(b)
>>> [3, 2, 1]
  • Related