Python – 将元组值列表转换为元组列表
给定一个字典,其值为元组列表,转换为元组的键映射列表。
Input : test_dict = {‘Gfg’ : [(5, 6, 7), (6, )], ‘is’ : [(5, 5, 2, 2, 6)], ‘best’ :[(7, )]}
Output : [(‘Gfg’, 5, 6, 7), (‘Gfg’, 6), (‘is’, 5, 5, 2, 2, 6), (‘best’, 7)]
Explanation : Keys grouped with values.
Input : test_dict = {‘Gfg’ : [(5, ), (6, )], ‘is’ : [(5, )], ‘best’ :[(7, )]}
Output : [(‘Gfg’, 5), (‘Gfg’, 6), (‘is’, 5), (‘best’, 7)]
Explanation : Keys grouped with values.
方法 #1:使用循环 + *运算符+ items()
这是可以执行此任务的方式之一。在此,我们使用循环遍历所有键,并通过使用 *运算符解包元组中的所有值来映射所有值的键。
Python3
# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using loop + * operator + items()
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
'is' : [(5, 5, 2, 2, 6)],
'best' :[(7, ), (9, 16)]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using items() to extract all the items of
# dictionary
res = []
for key, val in test_dict.items():
for ele in val:
res.append((key, *ele))
# printing result
print("The converted tuple list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using list comprehension + * operator + items()
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
'is' : [(5, 5, 2, 2, 6)],
'best' :[(7, ), (9, 16)]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# list comprehension encapsulates whole logic
# into one line
res = [(key, *ele) for key, sub in test_dict.items() for ele in sub]
# printing result
print("The converted tuple list : " + str(res))
The original dictionary is : {‘Gfg’: [(5, 6, 7), (1, 3), (6, )], ‘is’: [(5, 5, 2, 2, 6)], ‘best’: [(7, ), (9, 16)]}
The converted tuple list : [(‘Gfg’, 5, 6, 7), (‘Gfg’, 1, 3), (‘Gfg’, 6), (‘is’, 5, 5, 2, 2, 6), (‘best’, 7), (‘best’, 9, 16)]
方法 #2:使用列表理解 + *运算符+ items()
这是解决此问题的另一种方法。解决方法与上述方法类似。唯一的区别是使用列表理解提供单行解决方案。
Python3
# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using list comprehension + * operator + items()
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
'is' : [(5, 5, 2, 2, 6)],
'best' :[(7, ), (9, 16)]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# list comprehension encapsulates whole logic
# into one line
res = [(key, *ele) for key, sub in test_dict.items() for ele in sub]
# printing result
print("The converted tuple list : " + str(res))
The original dictionary is : {‘Gfg’: [(5, 6, 7), (1, 3), (6, )], ‘is’: [(5, 5, 2, 2, 6)], ‘best’: [(7, ), (9, 16)]}
The converted tuple list : [(‘Gfg’, 5, 6, 7), (‘Gfg’, 1, 3), (‘Gfg’, 6), (‘is’, 5, 5, 2, 2, 6), (‘best’, 7), (‘best’, 9, 16)]