2024-04-20 08:21:34 发布
网友
我正在尝试将包含项和计数的python字典转换为项列表
items = {"hello":2,"world":1}
至
["hello","hello","world"]
请帮助我如何处理这个逻辑
使用collections.Counter:
from collections import Counter items = {"hello": 2, "world": 1} result = list(Counter(items).elements()) print(result)
输出
['hello', 'hello', 'world']
或list comprehension:
result = [key for key, value in items.items() for _ in range(value)]
使用collections.Counter:
输出
或list comprehension:
相关问题 更多 >
编程相关推荐