0

I have a simple list:

a = [8, 5, 2, 20, 13, 14, 17, 13, 15, 21]

I can get the 5 greatest values in the list:

sorted(a)[-5:]

How could I get the indices of the 5 greatest values in the list?

So, the 5 greatest values of the list are [14, 15, 17, 20, 21] and these are at indices [9, 3, 6, 8, 5]. I'm sure there are multiple strategies to consider if there are duplicate values one might be to give their indices if they are near to other great values.

d3pd
  • 7,935
  • 24
  • 76
  • 127
  • Just for completeness, please add what your expected result would be. This will give you a [mcve] which is preferred. – Inbar Rose Apr 13 '16 at 14:00

6 Answers6

7

You can try this:

[x[0] for x in sorted(enumerate(a), key=lambda x: x[1])[-5:]]
freakish
  • 54,167
  • 9
  • 132
  • 169
1

You can do:

[a.index(x) for x in sorted(a)[-5:]]

Visit the docs and check the index function.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • Who marked this as bad? What's wrong with this solution? – sedavidw Apr 13 '16 at 14:02
  • @sedavidw I really wonder.. that's bad and sad. I can't know my mistake without an explanation of the downvote. – Maroun Apr 13 '16 at 14:02
  • 2
    `.index(x)` is both inefficient and incorrect in case of duplicates. I didn't downvote though. – freakish Apr 13 '16 at 14:03
  • @Maroun, Good answer, But try for `a = [1,1,1,1,2,2,2,3,3]` ... `index` is ALWAYS frowned upon as it fails for dupes. (imo, not worth a downvote though, not worth an upvote either) – Bhargav Rao Apr 13 '16 at 14:04
  • Thanks for the explanation! – sedavidw Apr 13 '16 at 14:05
  • Not really fair to down vote for that, especially considering you don't even know if that behavior fits the OP's needs or not. Rather than down voting you should have commented the question and asked for clarification before proceeding. – MrAlexBailey Apr 13 '16 at 14:06
0

len(sorted(a)) - 1 This will give you the index of the biggest element.

len(sorted(a)) - 2 would then give you the second biggest element and so on

JohWies
  • 107
  • 1
  • 6
0

Well, that partially depends on if you have duplicate values in your list.

If there are no duplicate values, I think the simplest answer is probably to get the greatest values in the way that you mentioned, and then for each one, find the index of that value with the index method of lists: [1,2,3].index(3)

TKoL
  • 13,158
  • 3
  • 39
  • 73
0

Short answer:

 map(itemgetter(0), sorted(enumerate(lst), key=itemgetter(1), reverse=True))[:5]

As a function:

from operator import itemgetter

def get_top_indices(lst, qnt=5):
    return map(itemgetter(0), sorted(enumerate(lst), key=itemgetter(1), reverse=True))[:qnt]

Example:

>>> get_top_indices([8, 5, 2, 20, 13, 14, 17, 13, 15, 21])
[9, 3, 6, 8, 5]
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
0
a = [8, 5, 2, 20, 13, 14, 17, 13, 15, 21]
b = sorted(a)[-5:]

c = [i for i , x in enumerate(a) if x in b]
NoorJafri
  • 1,787
  • 16
  • 27