Sort the list, then specify the element indices in the original order

I have an array of n numbers, for example [1,4,6,2,3] . The sorted array is [1,2,3,4,6] , and the indices of these numbers in the old array are 0, 3, 4, 1 and 2. How can I get an array of n numbers to find this array of indices?

My idea is to run order statistics for each item. However, since I have to rewrite this feature many times (in a contest), I wonder if there is a short way to do this.

+6
source share
4 answers
 >>> a = [1,4,6,2,3] >>> [b[0] for b in sorted(enumerate(a),key=lambda i:i[1])] [0, 3, 4, 1, 2] 

Explanation:

enumerate(a) returns an enumeration by tuples consisting of indices and values ​​in the original list: [(0, 1), (1, 4), (2, 6), (3, 2), (4, 3)]

Then sorted with key from lambda i:i[1] sorts based on the original values ​​(element 1 of each tuple).

Finally, understanding the list [b[0] for b in ... ] returns the original indexes (element 0 of each tuple).

+12
source

Here is another way:

 >>> sorted(xrange(len(a)), key=lambda ix: a[ix]) [0, 3, 4, 1, 2] 

This approach does not sort the source list, but its indexes (created using xrange ) using the source list as sort keys.

+1
source

Using numpy arrays instead of lists can be useful if you do a lot of statistics on the data. If you decide to do this, this will work:

 import numpy as np a = np.array( [1,4,6,2,3] ) b = np.argsort( a ) 

argsort () can work in lists too, but I believe that in this case it just copies the data to the array first.

+1
source

This should do the trick:

 from operator import itemgetter indices = zip(*sorted(enumerate(my_list), key=itemgetter(1)))[0] 
0
source

Source: https://habr.com/ru/post/974449/


All Articles