在Python数组中查找已排序元素的索引 [英] Finding the Index of sorted elements in Python Array
问题描述
我已经看到以下问题的答案:
是否可以通过使用元素的索引以降序排列numpy数组(或python列表)?(例如
I have seen answers to the question:
Is it possible to arrange a numpy array (or python list) by using the indexes of the elements in decreasing order? (eg. Finding the Index of N biggest elements in Python Array / List Efficiently)
一个非常简洁的答案似乎是(从上面的链接):
A very concise answer seems to be (from above link):
L = array([4, 1, 0, 8, 5, 2])
sorted(range(len(L)), key=lambda i:L[i])
这给出了已排序元素的位置(在原始数组中).
This gives the position (in the original array) of the sorted elements.
8-> 3
5-> 4
4-> 0
2-> 5
1-> 1
0-> 2
8 --> 3
5 --> 4
4 --> 0
2 --> 5
1 --> 1
0 --> 2
所以答案是:
[3, 4, 0, 5, 1, 2]
我追求的是元素的位置(在排序数组中):
What I am after is the position (in the sorted array) of the elements:
L = array([4, 1, 0, 8, 5, 2])
8-> 0
5-> 1
4-> 2
2-> 3
1-> 4
0-> 5
8 --> 0
5 --> 1
4 --> 2
2 --> 3
1 --> 4
0 --> 5
所以我想要:
[2, 4, 5, 0, 1, 3]
我意识到我可以从第一个示例中得到答案,并用它来得到我想要的(有点儿麻烦),但是有捷径吗?
I realise I could take the answer from the first example, and use that to get what I want (with a bit more fiddling) but is there a short cut?
效率不是问题.我只需要一些可以给我答案的东西.
Efficiency is not a concern. I just need something that gives me the answer.
推荐答案
您可以简单地两次使用技术来获取已排序列表中的索引:
You can simply use your technique twice to get the indices in the sorted list:
A=[4, 1, 0, 8, 5, 2]
B=sorted(range(len(A)),key=lambda x:A[x],reverse=True)
C=sorted(range(len(A)),key=lambda x:B[x])
print C
打印
[2, 4, 5, 0, 1, 3]
说明
想法是第一次迭代会产生一个列表:
Explanation
The idea is that the first iteration produces a list:
B = [3, 4, 0, 5, 1, 2]
给出排序序列的原始列表中的位置.
giving the locations in the original list of the sorted sequence.
换句话说,A [3] = 8是原始列表中的最大元素,A [4] = 5是下一个最大的元素,等等.
In other words, A[3]=8 is the largest element in the original list, A[4]=5 is the next largest, etc.
第二阶段然后将B中的这些索引重新排序为0、1、2、3、4、5的顺序,并生成C,其中C包含列表B中的索引.
The second stage then sorts these indices in B back into the order 0,1,2,3,4,5 and produces C which contains the index in the list B.
将B看作是将列表按降序排序,将C转变为原来的未排序顺序可能会有所帮助,同时跟踪排序列表中的索引.
It may help to think of B as sorting the list into descending order, and C as reversing the sort back into the original unsorted order, while keeping track of the indices in the sorted list.
这篇关于在Python数组中查找已排序元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!