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)
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 ( < ).
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.
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.
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)]
def position(a):
return sorted(range(len(a)), key=lambda k: a[k])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With