python列表中偶数位索引元素排序_在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

So the answer is:

[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

So I want :

[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

prints

[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.

In other words, A[3]=8 is the largest element in the original list, A[4]=5 is the next largest, etc.

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值