Python程序通过重复键对应的值时间将字典转换为列表
给定一个字典,其中键是字符,它们的组成值是数字,这里的任务是编写一个Python程序,通过重复键字符值次数将其转换为列表。
Input : test_dict = {‘g’ : 2, ‘f’ : 3, ‘g’ : 1, ‘b’ : 4, ‘e’ : 1, ‘s’ : 4, ‘t’ : 3}
Output : [‘g’, ‘f’, ‘f’, ‘f’, ‘b’, ‘b’, ‘b’, ‘b’, ‘e’, ‘s’, ‘s’, ‘s’, ‘s’, ‘t’, ‘t’, ‘t’]
Explanation : f is added 3 times in list.
Input : test_dict = {‘g’ : 2, ‘f’ : 3, ‘g’ : 1, ‘b’ : 4, ‘e’ : 1}
Output : [‘g’, ‘f’, ‘f’, ‘f’, ‘b’, ‘b’, ‘b’, ‘b’, ‘e’]
Explanation : f is added 3 times in list.
方法 1:使用循环和*运算符
在这种情况下,使用循环插入元素,并使用 *运算符处理出现的情况。
程序:
Python3
# initializing dictionary
test_dict = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = []
for key, val in test_dict.items():
# getting values using * operator
res += [key] * val
# printing result
print("The constructed list : " + str(res))
Python3
# initializing dictionary
test_dict = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# nested list comprehension to solve problem
res = [key for key, val in test_dict.items() for _ in range(val)]
# printing result
print("The constructed list : " + str(res))
输出:
The original dictionary is : {‘g’: 1, ‘f’: 3, ‘b’: 4, ‘e’: 1, ‘s’: 4, ‘t’: 3}
The constructed list : [‘g’, ‘f’, ‘f’, ‘f’, ‘b’, ‘b’, ‘b’, ‘b’, ‘e’, ‘s’, ‘s’, ‘s’, ‘s’, ‘t’, ‘t’, ‘t’]
方法 2:使用列表理解
这使用使用列表理解作为一个衬垫的嵌套循环方法来解决这个问题。根据需要尽可能多地迭代值。
程序:
蟒蛇3
# initializing dictionary
test_dict = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# nested list comprehension to solve problem
res = [key for key, val in test_dict.items() for _ in range(val)]
# printing result
print("The constructed list : " + str(res))
输出:
The original dictionary is : {‘g’: 1, ‘f’: 3, ‘b’: 4, ‘e’: 1, ‘s’: 4, ‘t’: 3}
The constructed list : [‘g’, ‘f’, ‘f’, ‘f’, ‘b’, ‘b’, ‘b’, ‘b’, ‘e’, ‘s’, ‘s’, ‘s’, ‘s’, ‘t’, ‘t’, ‘t’]