簡體   English   中英

如何用 python 中的順序替換列表中的所有項目?

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

讓我們看看這個列表:

L = [8,1,4,2]

我想用它們的順序替換它的元素。
預期結果:

[4,1,3,2]

以下腳本有效,但其雙 for 循環確實效率低下:

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

使用排序+枚舉

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

[4, 1, 3, 2]

這種方法是O(n log n) ,因為正在對數組進行排序。 如果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

[4, 1, 3, 5, 2]

使用雙端隊列的原因是為了使順序穩定,前 8 個有第一個 position,同時保持 popleft 操作O(1) ,因此算法保持O(n log n)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM