pythonlistunordered

How can I save the original index after sorting a list?


Let's say I have the following array:

a = [4,2,3,1,4]

Then I sort it:

b = sorted(A) = [1,2,3,4,4]

How could I have a list that map where each number was, ex:

position(b,a) = [3,1,2,0,4]

to clarify this list contains the positions not values)

(ps' also taking in account that first 4 was in position 0)


Solution

  • b = sorted(enumerate(a), key=lambda i: i[1])
    

    This results is a list of tuples, the first item of which is the original index and second of which is the value:

    [(3, 1), (1, 2), (2, 3), (0, 4), (4, 4)]