Python – 将频率字典转换为列表
有时,在使用Python字典时,我们可能会遇到需要根据字典的值构造列表的问题。此任务与查找频率相反,并且在日常编程和 Web 开发领域有应用。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {‘gfg’ : 3, ‘ide’ : 2}
Output : [‘gfg’, ‘gfg’, ‘gfg’, ‘ide’, ‘ide’]
Input : test_dict = {‘practice’ : 1, ‘write’ : 2, ‘ide’ : 4}
Output : [‘practice’, ‘write’, ‘write’, ‘ide’, ‘ide’, ‘ide’, ‘ide’]
方法#1:使用循环
这是解决这个问题的粗暴方法。在此,我们迭代字典并提取频率并以该频率复制元素。
# Python3 code to demonstrate working of
# Convert Frequency dictionary to list
# Using loop
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Convert Frequency dictionary to list
# Using loop
res = []
for key in test_dict:
for idx in range(test_dict[key]):
res.append(key)
# printing result
print("The resultant list : " + str(res))
The original dictionary : {‘is’: 2, ‘best’: 5, ‘gfg’: 4}
The resultant list : [‘is’, ‘is’, ‘best’, ‘best’, ‘best’, ‘best’, ‘best’, ‘gfg’, ‘gfg’, ‘gfg’, ‘gfg’]
方法#2:使用列表推导
该方法在工作方面与上述方法类似。这是上述方法的简写。
# Python3 code to demonstrate working of
# Convert Frequency dictionary to list
# Using list comprehension
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Convert Frequency dictionary to list
# Using list comprehension
res = [[key] * test_dict[key] for key in test_dict]
# printing result
print("The resultant list : " + str(res))
The original dictionary : {‘is’: 2, ‘best’: 5, ‘gfg’: 4}
The resultant list : [‘is’, ‘is’, ‘best’, ‘best’, ‘best’, ‘best’, ‘best’, ‘gfg’, ‘gfg’, ‘gfg’, ‘gfg’]