How do I find the sorted position/index of a list in python?

Question:

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?

Asked By: Michael

||

Answers:

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]

older (inefficient) answer

IIUC, you want the sorted rank:

sorted_list = sorted(your_list)
[sorted_list.index(x) for x in your_list]
Answered By: mozway

Sorting your list can be done with numpy:

numpy.argsort([2, 3, 5, 1, 4])
Answered By: Alexandre Mahdhaoui

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]
Answered By: Alain T.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.