Home  >  Article  >  Backend Development  >  How to use Python to obtain the new index after sorting a disordered list

How to use Python to obtain the new index after sorting a disordered list

WBOY
WBOYforward
2023-05-09 23:05:281810browse

For a list, sorting is very simple. To sort in forward order (from small to large) use

list.sort()

and to sort in reverse order (from large to small) use

list.sort(reverse=True)

. But if you are not limited to getting a sorted list, you also want to record the original next mark, then for a numpy.array, you can use

np.argsort()

For example, [1,3,2,5,6]

will become [1,2,3,5 after sorting ,6]

But if we want to know what the original subscript of the sorted result is (the answer is [0,2,1,3,4]), we can use np.argsort()

But if it is a simple list and you want to achieve this effect, you can use

# enumerate(x)会自动构造一个tuple(a,b)
# 其中a是index,b是list里index下标对应的具体的值,后面的x是代表一个虚拟变量,即tuple(a,b)
sorted_list = sorted(enumerate(list), key=lambda x:x[1])  # x[1]是因为在enumerate(a)中,a数值在第1位
result = [x[0] for x in sorted_list]

The result returned is the original index

If you want to achieve the one in the title, go one step further , that is, to get a new subscript after sorting the list, for example, for [1,5,2,8,3,4], you should get [0,4,1,5,2,3]

Then you can use

# enumerate(x)会自动构造一个tuple(a,b)
# 其中a是index,b是list里index下标对应的具体的值,后面的x是代表一个虚拟变量,即tuple(a,b)
# sorted_list = [(0,1),(2,2),(4,3),(5,4),(1,5),(3,8)]
sorted_list = sorted(enumerate(list), key=lambda x:x[1])  # x[1]是因为在enumerate(a)中,a数值在第1位
for i in range(len(sorted_list)):
    list[sorted_list[i][1]] = i

The above is the detailed content of How to use Python to obtain the new index after sorting a disordered list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete