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

2

8

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)

Noncooperation answered 1/4, 2020 at 11:37 Comment(1)
You can use numpy's argsort function.Editorialize
T
14
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)]
Trainee answered 1/4, 2020 at 11:40 Comment(3)
I might be tempted to take it one step further and unpack (if tuples are okay), eg: orig_pos, b = zip(*sorted(enumerate(a), key=lambda i: i[1]))Teacher
Sure, if the idea is to have two separate lists; but IMO it usually makes more sense to keep data together which belongs together.Trainee
Yup... all depends... just throwing it out there :)Teacher
S
2
def position(a):
    return sorted(range(len(a)), key=lambda k: a[k])
Sergiosergipe answered 1/4, 2020 at 11:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.