2

What is the most efficient way to extract to a list the indices corresponding to the n highest values of another list, while preserving the list we're extracting the indices from?

For example, let's say we have the following list of indices:

foo = [107,6,34,12,82]

If we requested the indices of the 2 highest values of the list foo, it should return us the following list:

bar = [0,4]

Here's what I'm running right now, it's really inefficient and not elegant at all and I don't really know how to improve it:

foo = [107, 6, 34, 12, 82]
tmp = list(foo)
bar = []
no_of_indices_wanted = int(input())
for n in range(no_of_indices_wanted):
    bar.append(foo.index(max(foo)))
    foo.pop(foo.index(max(foo)))
foo = tmp
bla
  • 1,840
  • 1
  • 13
  • 17
Rayan Hatout
  • 640
  • 5
  • 22

4 Answers4

2

You can use enumerate to annotate indices on each item, and then use heapq.nlargest to obtain the highest two of the list, after which you extract the indices into a list:

import heapq
from operator import itemgetter
print(list(map(itemgetter(0), heapq.nlargest(2, enumerate(foo), key=itemgetter(1)))))

This outputs: [0, 4]

blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Another approach would be:

foo = [107,6,34,12,82]
n=2
[i for i, x in sorted(enumerate(foo), key=lambda x: -x[1])[:n]]
#[0, 4]
zipa
  • 27,316
  • 6
  • 40
  • 58
  • This would work if there aren't two of the same highest numbers in the list, which may or may not be a valid assumption. – blhsing Sep 13 '18 at 02:42
0

You can sort tuples of (value, index) and then recover the indices.

def n_highest(lst, n):
    ordered = sorted([(value, idx) for idx, value in enumerate(lst)], reverse=True)
    return [idx for value, idx in ordered[:n]]

print(n_highest([107, 6, 34, 12, 82], 2))

Output

[0, 4]
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
-1

You can use the below approach too:

myList=[1,50,30,15,14]
sorted_ind_list=[]

for a in sorted((e,i) for i,e in enumerate(myList)):
   sorted_ind_list.append(a[1])

print(sorted_ind_list[0:2])

sort has Better performance over heap.

comparison

Jim Todd
  • 1,488
  • 1
  • 11
  • 15
  • This gives the highest two values, rather than the indices of the highest two values that the OP asks for. – blhsing Sep 13 '18 at 02:19