python - 在字典中按其键值重复每个成员而不使用 np.repeat?

标签 python dictionary

我有一个简单的数字字典及其各自的频率,是我结合两个列表制作的:

elements = [1, 2, 3, 4, 5]
frequency = [5, 4, 3, 2, 1]

combined = {ele: freq for ele, freq in zip(elements, frequency)}

>>> print(combined)
{1: 5, 2: 4, 3: 3, 4: 2, 5: 1}

现在我想要每个 ele重复其 freq并保存在新列表中。理想情况下,最好是使用 repeat()来自 numpy。

repeated = list(np.repeat(key, val) for key, val in sorted(combined.items()))  # If a dict needs sorting

>>> print(repeated)
[1,1,1,1,1,2,2,2,2, ... ,4,4,5]

但是,我想使用重复来执行此操作。什么是继续的好方法?

最佳答案

使用collections.Counter的一种方法:

d = {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}
list(Counter(d).elements())

输出:

[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]

关于python - 在字典中按其键值重复每个成员而不使用 np.repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59747545/

相关文章:

list - 如何将列表与特定键/值作为主机变量进行组合/匹配

python - 在 Python 中将一部分 geojson 对象合并到另一个对象中

python - 使用子进程从 python 脚本编译 C++ 程序

Python pandas dataframe - 条件分组依据

Python setuptools 正在从 Windows 上的路径参数中删除斜杠

python - 获取购买次数最多的前 10 件商品作为列表

c# - 编译器会优化集合初始化吗?

python - 在 Python 中初始化/创建/填充字典的字典

Python - 字典相交列表

python - 通过将另一列与第二个 DataFrame 进行比较来替换一列中的值