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

两盒软妹~` 提交于 2020-01-20 04:23:05

问题


I need your help to solve a problem.

I want to convert a dictionary d = {key1:value1, key2:value2} into list= [keys1, keys1, ... (value1 times), keys2, ... (value2 times)] without using a nested loop.

Example:

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

The code should produce the output:

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

This is what I have:

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

Which gives: [4, 33, 1212], but should give [4, 3, 3, 12, 12].

The complexity should be O(n).


回答1:


The easiest solution is to use collections.Counter. It features an elements() method that yields all elements with the correct count:

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

If you want to implement this yourself, I think the most readable version is this for loop:

from itertools import repeat

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



回答2:


Just use repeat, which yields an element a specified number of times, with chain to combine everything together:

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()))

Output:

[4, 3, 3, 12, 12]



回答3:


You can use a comprehension like below:

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

Code:

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]

To avoid all those fancy splits and map, you can go for:

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

which also outputs the desired output.




回答4:


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)

Output:

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



回答5:


For less complex amd more readable soultion, in addition, no extra packages are required, your code could be as the following:

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

print(nums2)

which outputs with the following:

[4, 3, 3, 12, 12]


来源:https://stackoverflow.com/questions/55439508/how-to-convert-a-dictionary-to-a-list-of-keys-with-repeat-counts-given-by-the-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!