将包含项目和计数的字典转换为项目列表

2024-04-20 08:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将包含项和计数的python字典转换为项列表

items = {"hello":2,"world":1}

["hello","hello","world"]

请帮助我如何处理这个逻辑


Tags: hello列表world字典items逻辑计数
1条回答
网友
1楼 · 发布于 2024-04-20 08:21:34

使用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)]

相关问题 更多 >