在 Python 中找出列表中元素的相对顺序


我们有一个由整数构成的列表。我们需要找出相对顺序,即如果按升序对它们进行排序,则我们需要找出它们所在位置的索引。

已排序的和索引

我们首先对整个列表进行排序,然后找出它们在排序后的每个索引。

示例

 实时演示

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and index()
res = [sorted(listA).index(i) for i in listA]
# printing result
print("list with relative ordering of elements : \n",res)

输出

运行以上代码,得到以下结果 -

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

已枚举和已排序的

使用枚举和排序函数,我们检索每个元素,然后创建一个包含枚举和已排序函数的字典容器。我们通过映射函数获取通过此容器的每个元素。

示例

 实时演示

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and enumerate
temp = {val: key for key, val in enumerate(sorted(listA))}
res = list(map(temp.get, listA))
# printing result
print("list with relative ordering of elements : \n",res)

输出

运行以上代码,得到以下结果 -

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

更新日期: 04-6 月-2020

387 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.