Home > Backend Development > Python Tutorial > 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
Release: 2023-05-09 23:05:28
forward
1827 people have browsed it

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

list.sort()
Copy after login

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

list.sort(reverse=True)
Copy after login

. 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()
Copy after login

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]
Copy after login

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
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template