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 ?
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....
Is there any built-in function in Python or numpy to deal with it ?
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]
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)
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]