python - 字典键*值到python中的列表

标签 python python-3.x list dictionary

我的字典如下:

the_dict = {'1': 2,
 '2': 4,
 '3': 3,
 '8': 3,
 '9': 3,
 '10': 4,
 '14': 4}

我需要将键乘以值来创建一个长的平面列表。 我的尝试如下,但它搞砸了 10 和 14:

new_target = []
for k, v in zip(the_dict.keys(), the_dict.values()):
    new_target += list(k*v)

此代码产生: ['1', '1', '2', '2', '2', '2', '3', '3', '3', '8', '8', '8 ','9','9','9','1','0','1','0','1','0','1','0','1', '4', '1', '4', '1', '4', '1', '4']

该代码接近,但由于 10 和 14 上的以下行为,它不起作用; list("10"*2) 产生 ['1', '0', '1', '0'] 而不是所需的 ['10 ', '10'].

如何创建所需的列表?

最佳答案

添加到 M-Chen-3 的答案,您还可以使用 list comprehension 将其压缩为类似这样的内容:

new_target = [k for k, v in the_dict.items() for _ in range(v)]

关于python - 字典键*值到python中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65569920/

相关文章:

python - Perl 正则表达式与 Python 正则表达式非捕获似乎工作方式不同

python - 列表和 numpy 数组之间的比较

Python 队列 - task_done() 的数量

python - SQLAlchemy db.drop_all() 给出 AttributeError : 'NoneType' object has no attribute 'lower'

list - SwiftUI 异步数据获取

c# - 从列表 2 中过滤列表 1

python - Pytorch:如何从 2D 矢量/图像预测 1D 矢量?

python - 在 Python 中使用 '__rsub__' 方法的典型实例是什么?

python - 将列表转换为链表

python - 合并特定列上的重复行