+4 votes
in Programming Languages by (40.5k points)
I want to sort a list in decreasing order and get the original indices of all elements in the sorted list. How can I do this?

E.g.

original list: [10,5,15]

sorted list: [15,10,5]

answer_indices: [2,0,1]

1 Answer

+2 votes
by (351k points)
selected by
 
Best answer

You can use argsort() function of the Numpy. This function returns an array of indices that would sort the original list in increasing order. You need to reverse the array of indices to get the original list in decreasing order.

Here is an example:

import numpy as np
np.random.seed(7)
x = np.random.randint(10, 500, 10)
print("original list: {0}".format(x))
idx = np.argsort(x)[::-1]   # reverse the array of indices
print("Indices of list sorted in decreasing order: {0}".format(idx))
print("list sorted in decreasing order: {0}".format(x[idx]))

The above code will print the following output:

original list: [185 206  35  77 221 417 113 358 195 408]
Indices of list sorted in decreasing order: [5 9 7 4 1 8 0 6 3 2]
list sorted in decreasing order: [417 408 358 221 206 195 185 113  77  35]


...