Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list then give the indexes of the elements in their original order

I have an array of n numbers, say [1,4,6,2,3]. The sorted array is [1,2,3,4,6], and the indexes of these numbers in the old array are 0, 3, 4, 1, and 2. What is the best way, given an array of n numbers, to find this array of indexes?

My idea is to run order statistics for each element. However, since I have to rewrite this function many times (in contest), I'm wondering if there's a short way to do this.

like image 904
neutralino Avatar asked Aug 28 '14 02:08

neutralino


1 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 over tuples consisting of the indexes and values in the original list: [(0, 1), (1, 4), (2, 6), (3, 2), (4, 3)]

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

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

like image 182
user2085282 Avatar answered Oct 05 '22 21:10

user2085282