How to get indices of a sorted array in Python
If you are using numpy, you have the argsort() function available:
>>> import numpy>>> numpy.argsort(myList)array([0, 1, 2, 4, 3])
http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
This returns the arguments that would sort the array or list.
Something like next:
>>> myList = [1, 2, 3, 100, 5]>>> [i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])][0, 1, 2, 4, 3]
enumerate(myList)
gives you a list containing tuples of (index, value):
[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]
You sort the list by passing it to sorted
and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda
is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...]
list comprehension.