在 Python 中获取排序列表的索引

要获取排序列表的索引:

  1. 使用 range() 类创建列表长度的范围对象。
  2. 使用 sorted() 函数获取排序列表的索引。
  3. 设置 key 参数以指定排序条件。
a_list = ['a', 'b', 'd', 'c']

indices = sorted(
    range(len(a_list)),
    key=lambda index: a_list[index]
)

print(indices)  # ?️ [0, 1, 3, 2]


sorted_list = [a_list[index] for index in indices]
print(sorted_list)  # ?️ ['a', 'b', 'c', 'd']

在 Python 中获取排序列表的索引

如果我们使用 numpy 向下滚动到下一个子标题。

索引列表存储对列表进行排序的索引。

sorted 函数接受一个迭代并从迭代中的项目返回一个新的排序列表。

a_list = ['a', 'b', 'd', 'c']

sorted_list = sorted(a_list)
print(sorted_list) # ?️ ['a', 'b', 'c', 'd']

我们使用 range() 类来获取列表长度的 range 对象。

a_list = ['a', 'b', 'd', 'c']

print(list(range(len(a_list)))) # ?️ [0, 1, 2, 3]

range() 函数通常用于循环特定次数。

sorted() 函数采用一个可选的键参数,可用于按不同的标准进行排序。

a_list = ['a', 'b', 'd', 'c']

indices = sorted(
    range(len(a_list)),
    key=lambda index: a_list[index]
)

print(indices)  # ?️ [0, 1, 3, 2]

可以将 key 参数设置为确定排序标准的函数。

我们对索引进行排序,但我们使用的标准是列表中的每个值。

使用 range 对象中的每个索引调用 lambda 函数,并使用相应的列表项作为排序标准。

如果我们还需要对列表进行排序,则可以使用列表推导。

a_list = ['a', 'b', 'd', 'c']

indices = sorted(
    range(len(a_list)),
    key=lambda index: a_list[index]
)
print(indices)  # ?️ [0, 1, 3, 2]


sorted_list = [a_list[index] for index in indices]
print(sorted_list)  # ?️ ['a', 'b', 'c', 'd']

我们使用列表推导来迭代索引列表并返回每个列表项。

列表推导 用于对每个元素执行一些操作或选择满足条件的元素子集。

相同的方法可用于获取已排序数字列表的索引。

a_list = [1, 2, 4, 3]

indices = sorted(
    range(len(a_list)),
    key=lambda index: a_list[index]
)

print(indices)  # ?️ [0, 1, 3, 2]


sorted_list = [a_list[index] for index in indices]
print(sorted_list)  # ?️ [1, 2, 3, 4]

在 Python 中获取排序列表的索引

或者,我们可以使用 numpy.argsort() 方法。


使用 numpy.argsort() 获取排序列表的索引

使用 numpy.argsort() 方法获取排序列表的索引,例如 indices = np.argsort(a_list)。 numpy.argsort() 方法返回对类数组对象进行排序的索引。

import numpy as np

a_list = ['a', 'b', 'd', 'c']

indices = np.argsort(a_list)
print(indices)  # ?️ [0 1 3 2]


sorted_list = [a_list[index] for index in indices]
print(sorted_list)  # ?️ ['a', 'b', 'c', 'd']

在 Python 中获取排序列表的索引

numpy.argsort 方法接受一个类似数组的对象并返回对数组进行排序的索引。

indices 变量将索引存储在数组中,但如果需要将数组转换为列表,可以使用 tolist() 方法。

import numpy as np

a_list = ['a', 'b', 'd', 'c']

indices = np.argsort(a_list).tolist()
print(indices)  # ?️ [0, 1, 3, 2]


sorted_list = [a_list[index] for index in indices]
print(sorted_list)  # ?️ ['a', 'b', 'c', 'd']

tolist() 方法将数组转换为列表。