1

For example:

a = [1,5,6,2,3]

result = most_find(a, 3)

reslut
[2,1,4]  # the index of 6, 5, 3 in a

I know how to implement this function with complex way....

My question

Is there any built-in function in Python or numpy to deal with it ?

DeDao233
  • 65
  • 7
  • 4
    Does this answer your question? [How do I get indices of N maximum values in a NumPy array?](https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array) – sushanth Jun 20 '20 at 03:46
  • Yeah, thank you ! It's a easy way to work – DeDao233 Jun 20 '20 at 03:59
  • If it is already a `numpy` array, then the linked `argsort` or `argpartition` should be fastest. But if a list, then a list sort method is probably better. – hpaulj Jun 20 '20 at 04:00
  • @hpaulj, Okay, i get it ! Thanks. I was thinking this question, the direct way maybe more better – DeDao233 Jun 20 '20 at 05:22

3 Answers3

1

There is a built-in linked by Sushanth but you could also implement it like so: sorted(range(len(a)), key=lambda i: -a[i])[:3]

Ash
  • 137
  • 1
  • 10
1

Sort the index by value,

def most_find(sequence, n):
    lst = sorted(range(len(sequence)), key=lambda x:sequence[x], reverse=True)
    return lst[:n]

a = [1, 5, 6, 2, 3]
result = most_find(a, 3)

print(result)
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
0

Is there any built-in function in Python or numpy to deal with it?

As a matter of fact, there is! It's called numpy.argsort():

import numpy as np

a = [1, 5, 6, 2, 3]

print(np.array(a).argsort()[-3:][::-1]) # If you want to list the indexes of the 4 greatest numbers, change the -3 to -4, etc.

Output:

[2 1 4]
Red
  • 26,798
  • 7
  • 36
  • 58