[英]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.我想将字典
d = {key1:value1, key2:value2}
转换为list= [keys1, keys1, ... (value1 times), keys2, ... (value2 times)]
而不使用嵌套循环。
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]
.其中给出:
[4, 33, 1212]
,但应该给出[4, 3, 3, 12, 12]
。
The complexity should be O(n).复杂度应该是 O(n)。
The easiest solution is to use collections.Counter
.最简单的解决方案是使用
collections.Counter
。 It features an elements()
method that yields all elements with the correct count:它具有一个
elements()
方法,可生成具有正确计数的所有元素:
>>> 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:如果你想自己实现这个,我认为最易读的版本是这个
for
循环:
from itertools import repeat
result = []
for k, count in d1.items():
result += repeat(k, count)
Just use repeat
, which yields an element a specified number of times, with chain
to combine everything together:只需使用
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()))
Output:输出:
[4, 3, 3, 12, 12]
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:为了避免所有那些花哨的 splits 和
map
,你可以去:
[k for k, v in d1.items() for _ in range(v)]
which also outputs the desired output.它还输出所需的输出。
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']
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.