This question already has answers here:
How to get indices of a sorted array in Python
(11个答案)
5年前关闭。
例如,如果我有不同项目的列表:
L = [100,55,104,400]
可以重述“相对”顺序:
R = [1,0,2,3]
我不确定如何将L转换为R。起初,我只是尝试从所有内容中减去min(L),但这并没有将数据“压缩”为相对顺序。
我正在寻找一种有效的解决方案(不是O(n2))。
python大神给出的解决方案
您可以尝试结合使用列表理解,zip
和sorted
:
>>> [i[1] for i in sorted(zip(L, range(4)))]
[1, 0, 2, 3]
这是O(nlogn),因为您只需要排序一次。