python列表可以不按顺序查找元素_在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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值