简体   繁体   中英

How do I find the sorted position/index of a list 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?

IIUC, you want the sorted rank:

sorted_list = sorted(your_list)
[sorted_list.index(x) for x in your_list]

可以使用 numpy 对列表进行排序:

numpy.argsort([2, 3, 5, 1, 4])

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM