在 Python 中获取排序列表的索引
要获取排序列表的索引:
- 使用 range() 类创建列表长度的范围对象。
- 使用 sorted() 函数获取排序列表的索引。
- 设置 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']
如果我们使用 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]
或者,我们可以使用 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']
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() 方法将数组转换为列表。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。