For example, I have a list:
[12, 1205, 102, 6]
I want to get
[1, 3, 2, 0]
Because this is the position they are supposed to be in if the list is sorted.
How can I achieve this in python?
For example, I have a list:
[12, 1205, 102, 6]
I want to get
[1, 3, 2, 0]
Because this is the position they are supposed to be in if the list is sorted.
How can I achieve this in python?
Use a double numpy.argsort, or self-indexing:
l = [12, 1205, 102, 6]
out = np.argsort(np.argsort(l)).to_list()
# or
x = np.argsort(l)
out = x[x]
Output: [1, 3, 2, 0]
IIUC, you want the sorted rank:
sorted_list = sorted(your_list)
[sorted_list.index(x) for x in your_list]
You can get a list of indexes in the order of sorted values using the sorted() function, then use this to set the positions in the resulting list:
L = [12, 1205, 102, 6]
P = sorted(range(len(L)),key=L.__getitem__) # positions in sorted order
S = [None]*len(L) # resulting list
for p,i in enumerate(P): S[i]=p # assign position at original indexes
print(S) # [1, 3, 2, 0]
The equivalent solution using numpy could look like this:
S = np.zeros(len(L),dtype=np.int) # prepare resulting array
S[np.argsort(L)] = np.arange(len(L)) # assign positions at indexes
print(S) # array([1, 3, 2, 0])
S array, instead of just using a list comprehension for clarityp values at the appropriate index in S using a comprehension (i.e. appending), I would need to sort P a second time. I you print i and p inside the for loop, you will see that the assignments are not performed in sequential order.Sorting your list can be done with numpy:
numpy.argsort([2, 3, 5, 1, 4])