从字符串和列表创建元组 - Python
有时,我们可能会遇到需要使用来自不同容器的元素构建一个新容器的问题。这种问题可能发生在我们使用不同类型数据的领域。让我们讨论将字符串和列表数据转换为元组的方法。
方法 #1 : 使用 List 转换为 tuple + tuple()
在此方法中,我们将字符串转换为列表,然后附加到目标列表,然后使用 tuple() 将此结果列表转换为元组。
# Python3 code to demonstrate working of
# Construct tuple from string and list
# using list conversion to tuple + tuple()
# initialize list and string
test_list = ["gfg", "is"]
test_str = "best"
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Construct tuple from string and list
# using list conversion to tuple + tuple()
res = tuple(test_list + [test_str])
# printing result
print("The aggregated tuple is : " + str(res))
输出 :
The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')
方法#2:使用元组转换为元组+ tuple()
这是可以执行此任务的另一种方式。在此,我们将字符串和列表都转换为元组并将它们添加到结果元组中。这种方法比上述方法更有效。
# Python3 code to demonstrate working of
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
# initialize list and string
test_list = ["is", "best"]
test_str = "gfg"
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
res = (test_str, ) + tuple(test_list)
# printing result
print("The aggregated tuple is : " + str(res))
输出 :
The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')