Python程序通过在每个元素后添加给定的字符串来将元组转换为列表
给定一个元组。任务是通过在每个元素后添加给定的字符串将其转换为 List。
例子:
Input : test_tup = (5, 6, 7), K = "Gfg"
Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg']
Explanation : Added "Gfg" as succeeding element.
Input : test_tup = (5, 6), K = "Gfg"
Output : [5, 'Gfg', 6, 'Gfg']
Explanation : Added "Gfg" as succeeding element.
方法 #1:使用列表推导
在此,我们为元组的每个元素和一个后续元素构造一个元组,然后运行一个嵌套循环以使用列表理解来展平每个构造的元组。
Python3
# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using list comprehension
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
# printing original tuple
print("The original tuple is : ", test_tup)
# initializing K
K = "Gfg"
# list comprehension for nested loop for flatten
res = [ele for sub in test_tup for ele in (sub, K)]
# printing result
print("Converted Tuple with K : ", res)
Python3
# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using chain.from_iterable() + list() + generator expression
from itertools import chain
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
# printing original tuple
print("The original tuple is : ", test_tup)
# initializing K
K = "Gfg"
# list comprehension for nested loop for flatten
res = list(chain.from_iterable((ele, K) for ele in test_tup))
# printing result
print("Converted Tuple with K : ", res)
输出:
The original tuple is : (5, 6, 7, 4, 9)
Converted Tuple with K : [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg’]
方法 #2:使用 chain.from_iterable() + list() + 生成器表达式
这与上述方法类似,不同之处在于通过使用chain.from_iterable() 进行展平来避免嵌套循环。
Python3
# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using chain.from_iterable() + list() + generator expression
from itertools import chain
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
# printing original tuple
print("The original tuple is : ", test_tup)
# initializing K
K = "Gfg"
# list comprehension for nested loop for flatten
res = list(chain.from_iterable((ele, K) for ele in test_tup))
# printing result
print("Converted Tuple with K : ", res)
输出:
The original tuple is : (5, 6, 7, 4, 9)
Converted Tuple with K : [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg’]