并按值给出重复计数

并按值给出重复计数

本文介绍了如何将字典转换为键列表,并按值给出重复计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要您的帮助来解决问题.

I need your help to solve a problem.

我想将字典d = {key1:value1, key2:value2}转换为list= [keys1, keys1, ... (value1 times), keys2, ... (value2 times)]而不使用嵌套循环.

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

示例:

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

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

复杂度应为O(n).

推荐答案

最简单的解决方案是使用 collections.Counter .它具有 elements()方法,该方法可以产生全部计数正确的元素:

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]

如果您想自己实现这一点,我认为最易读的版本是for循环:

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)

这篇关于如何将字典转换为键列表,并按值给出重复计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:35