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 ?

4
  • 4
    Does this answer your question? How do I get indices of N maximum values in a NumPy array? Commented Jun 20, 2020 at 3:46
  • Yeah, thank you ! It's a easy way to work Commented Jun 20, 2020 at 3: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. Commented Jun 20, 2020 at 4:00
  • @hpaulj, Okay, i get it ! Thanks. I was thinking this question, the direct way maybe more better Commented Jun 20, 2020 at 5:22

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.