排序列表后如何保存原始索引? [英] How can I save the original index after sorting a list?

查看:52
本文介绍了排序列表后如何保存原始索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数组:

a = [4,2,3,1,4]

然后我对其进行排序:

b = sorted(A) = [1,2,3,4,4]

我怎么能找到一个列表,列出每个数字的位置,例如:

How could I have a list that map where each number was, ex:

position(b,a) = [3,1,2,0,4]

以澄清此列表包含的位置不是值)

to clarify this list contains the positions not values)

(ps还考虑到前4个位于位置0)

(ps' also taking in account that first 4 was in position 0)

推荐答案

b = sorted(enumerate(a), key=lambda i: i[1])

这将产生一个元组列表,其中第一项是原始索引,第二项是值:

This results in a list of tuples, the first item of which is the original index and second of which is the value:

[(3, 1), (1, 2), (2, 3), (0, 4), (4, 4)]

这篇关于排序列表后如何保存原始索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆