Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 737
user8920367 Avatar asked Apr 01 '20 11:04

user8920367


People also ask

Does sorted () modify the original list?

The sort() method sorts the original list in place. It means that the sort() method modifies the order of elements in the list. By default, the sort() method sorts the elements of a list using the less-than operator ( < ).

How do you get the indices of a sorted array?

We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that that would sort the array.

How do you sort a list by index in Python?

Method #1 : Using sort() + lambda sort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index.


2 Answers

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)]
like image 159
deceze Avatar answered Sep 26 '22 15:09

deceze


def position(a):
    return sorted(range(len(a)), key=lambda k: a[k])
like image 34
Ryohei Namiki Avatar answered Sep 23 '22 15:09

Ryohei Namiki