[英]What is the fastest way to convert a dictionary frequency to list in Python?
我的字典頻率如下:
freq = {'a': 1, 'b': 2, 'c': 3}
它只是意味着我有一個a
、兩個b
和三個c
。
我想把它轉換成一個完整的列表:
lst = ['a', 'b', 'b', 'c', 'c', 'c']
這樣做的最快方式(省時)或最緊湊的方式(節省空間)是什么?
是的,但前提是項目是(或可以表示為)整數,並且最小和最大項目之間的項目數足夠接近兩者之間的差異,在這種情況下,您可以使用桶排序,從而導致O(n)時間復雜度,其中n是最小和最大項目之間的差異。 這將比使用其他排序算法更有效,平均時間復雜度為O(n log n) 。
在List = [1, 4, 5, 2, 6, 7, 9, 3]
正如你的問題一樣,當知道1
是最小的項目時,使用桶排序確實更有效,並且9
是最大的項目,因為范圍之間只缺少8
。 以下示例使用collections.Counter
來說明輸入列表中可能存在重復項的可能性:
from collections import Counter
counts = Counter(List)
print(list(Counter({i: counts[i] for i in range(1, 10)}).elements()))
這輸出:
[1, 2, 3, 4, 5, 6, 7, 9]
讓我們將其分解為兩次O(N)傳遞:一次用於對數字進行編目,另一次用於創建排序列表。 我更新了變量名稱; 鑒於內置類型list
, List
是一個特別糟糕的選擇。 我還為每個值添加了 10,因此您可以看到低端偏移是如何工作的。
coll = [11, 14, 15, 12, 16, 17, 19, 13]
last = 19
first = 11
offset = first
size = last-first+1
# Recognize all values in a dense "array"
need = [False] * size
for item in coll:
need[item - offset] = True
# Iterate again in numerical order; for each True value, add that item to the new list
sorted_list = [idx + offset for idx, needed_flag in enumerate(need) if needed_flag]
print(sorted_list)
輸出:
[11, 12, 13, 14, 15, 16, 17, 19]
我通常使用的最緊湊的方式是列表理解——
lst = ['a', 'b', 'b', 'c', 'c', 'c']
freq = {i: 0 for i in lst}
for i in lst: freq[i] += 1
空間復雜度 - O(n)
時間復雜度 - O(n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.