将字典转换为具有基于值的长度的列表 [英] Convert dictionary into list with length based on values
本文介绍了将字典转换为具有基于值的长度的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字典
d = {1: 3, 5: 6, 10: 2}
我想将其转换为包含字典键的列表.每个键应重复与其关联值相同的次数.
I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.
我已经编写了完成此工作的代码:
I've written this code that does the job:
d = {1: 3, 5: 6, 10: 2}
l = []
for i in d:
for j in range(d[i]):
l.append(i)
l.sort()
print(l)
输出:
[1, 1, 1, 5, 5, 5, 5, 5, 5, 10, 10]
但是我希望它能成为列表理解者.该怎么办?
But I would like it to be a list comprehension. How can this be done?
推荐答案
您可以使用列表理解来实现:
You can do it using a list comprehension:
[i for i in d for j in range(d[i])]
产量:
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
您可以再次对其进行排序以获得所需的列表.
You can sort it again to get the list you were looking for.
这篇关于将字典转换为具有基于值的长度的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文