简体   繁体   English

如何用 python 中的顺序替换列表中的所有项目?

[英]How to replace all items in a list with their order in python?

Let's take this list:让我们看看这个列表:

L = [8,1,4,2]

I would like to replace its elements with their order.我想用它们的顺序替换它的元素。
Expected result:预期结果:

[4,1,3,2]

The following script works but is really unefficient with its double for loop:以下脚本有效,但其双 for 循环确实效率低下:

L_result = []
for i in L :
    order = 1
    for j in L :
        if i > j :
            order += 1
    L_result.append(order)

Use sorted + enumerate :使用排序+枚举

L = [8, 1, 4, 2]

positions = {e: i for i, e in enumerate(sorted(L), 1)}
result = [positions[e] for e in L]

print(result)

Output Output

[4, 1, 3, 2]

This approach is O(n log n) since is sorting the array.这种方法是O(n log n) ,因为正在对数组进行排序。 If L have duplicates values, you can do the following:如果L有重复值,您可以执行以下操作:

from collections import defaultdict, deque

L = [8, 1, 4, 8, 2]

positions = defaultdict(deque)
for i, e in enumerate(sorted(L), 1):
    positions[e].append(i)

result = [positions[e].popleft() for e in L]

print(result)

Output Output

[4, 1, 3, 5, 2]

The reason for using a deque is to make order stable, the first 8 has the first position, while at the same time keeping the popleft operation O(1) , therefore the algorithm remains O(n log n) .使用双端队列的原因是为了使顺序稳定,前 8 个有第一个 position,同时保持 popleft 操作O(1) ,因此算法保持O(n log n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM