Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...