user8920367
user8920367

Reputation: 105

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)

Upvotes: 8

Views: 5386

Answers (2)

deceze
deceze

Reputation: 522461

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)]

Upvotes: 14

user13177201
user13177201

Reputation:

def position(a):
    return sorted(range(len(a)), key=lambda k: a[k])

Upvotes: 2

Related Questions