簡體   English   中英

如何將字典轉換為鍵列表,並由值給出重復計數?

[英]How to convert a dictionary to a list of keys, with repeat counts given by the values?

我需要你的幫助來解決問題。

我想將字典d = {key1:value1, key2:value2}轉換為list= [keys1, keys1, ... (value1 times), keys2, ... (value2 times)]而不使用嵌套循環。

例子:

d1 = {4: 1, 3: 2, 12: 2}

代碼應該產生輸出:

l = [4, 3, 3, 12, 12]

這就是我所擁有的:

for key, value in nums1.items():
        temp = (str(key))*value
        nums2.append(int(temp))
print(nums2)

其中給出: [4, 33, 1212] ,但應該給出[4, 3, 3, 12, 12]

復雜度應該是 O(n)。

最簡單的解決方案是使用collections.Counter 它具有一個elements()方法,可生成具有正確計數的所有元素:

>>> from collections import Counter
>>> list(Counter(d1).elements())
[4, 3, 3, 12, 12]

如果你想自己實現這個,我認為最易讀的版本是這個for循環:

from itertools import repeat

result = []
for k, count in d1.items():
    result += repeat(k, count)

只需使用repeat ,它會產生指定次數的元素,並使用chain將所有內容組合在一起:

from itertools import chain, repeat

source = {4: 1, 3: 2, 12: 2}

list(chain.from_iterable(repeat(element, times) for element, times in source.items()))

輸出:

[4, 3, 3, 12, 12]

您可以使用如下理解:

list(chain.from_iterable(map(int, ((str(k) + ',') * v).split(',')[:-1]) for k, v in d1.items()))

代碼

from itertools import chain

d1 = {4: 1, 3: 2, 12: 2}

print(list(chain.from_iterable(map(int, ((str(k) + ',') * v).split(',')[:-1]) for k, v in d1.items())))
# [4, 3, 3, 12, 12]

為了避免所有那些花哨的 splits 和map ,你可以去:

[k for k, v in d1.items() for _ in range(v)]

它還輸出所需的輸出。

d1={4:1,3:2,12:2} 
ans =[]
for key,value in d1.items():
    ans.append((str(key),)*value)
print(ans)
flattened = []
list(flattened.extend(item) for item in ans)
print(flattened)

輸出:

[('4',), ('3', '3'), ('12', '12')]
['4', '3', '3', '12', '12']

對於不太復雜和更具可讀性的靈魂,另外,不需要額外的包,你的代碼可以如下:

nums1 = {4: 1, 3: 2, 12: 2} 
nums2 = []
for key, value in nums1.items():
    nums2 += [key]*value

print(nums2)

輸出如下:

[4, 3, 3, 12, 12]

暫無
暫無

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

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