在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]
用枚举和排序
使用枚举和排序函数,我们检索每个元素,然后创建一个包含枚举和排序函数的字典容器。我们使用map函数通过该容器获取每个元素。
示例
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]
热门推荐
9 祝福语简短古诗词
10 国庆中秋祝福语简短搞笑
11 学生开心成语祝福语简短
12 生日宝宝祝福语简短独特
13 喜事敬酒祝福语简短精辟
14 开店大吉文案祝福语简短
15 修祖屋祝福语简短
16 春季祝福语女生文案简短
17 六一祝福语简短感动女生
18 婆婆生日祝福语短语简短