Skip to content Skip to sidebar Skip to footer

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,

Solution 1:

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

This results in 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)]

Solution 2:

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

Post a Comment for "How Can I Save The Original Index After Sorting A List?"