+3 votes
in Programming Languages by (18.7k points)
After sorting a list in ascending order, the indices of elements in the sorted list may be different from their indices in the unsorted list. I want to know the original indices of elements in the sorted list. Is there any function that returns indices that would sort an array/list?

E.g.

If the unsorted list is [54,12,76,23,45,9,23,1], I want [7, 5, 1, 3, 6, 4, 0, 2] as the answer.

1 Answer

0 votes
by (32.8k points)

You can use Numpy's argsort() function. It returns the indices that would sort the list/array. Thus you will get the original indices of elements.

Here is an example:

>>> import numpy as np
>>> aa=[54,12,76,23,45,9,23,1]
>>> idx=np.argsort(aa)
>>> idx
array([7, 5, 1, 3, 6, 4, 0, 2])

...