Python – 两个字符串元组的连接
有时,在处理记录时,我们可能会遇到一个问题,我们可能需要执行元组的字符串连接。在白天编程中可能会出现此问题。让我们讨论可以执行此任务的某些方式。
方法 #1:使用zip()
+ 生成器表达式
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式执行字符串连接的任务,每个元组的映射索引由 zip() 完成。
# Python3 code to demonstrate working of
# Tuple String concatenation
# using zip() + generator expression
# initialize tuples
test_tup1 = ("Manjeet", "Nikhil", "Akshat")
test_tup2 = (" Singh", " Meherwal", " Garg")
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Tuple String concatenation
# using zip() + generator expression
res = tuple(ele1 + ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
# printing result
print("The concatenated tuple : " + str(res))
输出 :
The original tuple 1 : ('Manjeet', 'Nikhil', 'Akshat')
The original tuple 2 : (' Singh', ' Meherwal', ' Garg')
The concatenated tuple : ('Manjeet Singh', 'Nikhil Meherwal', 'Akshat Garg')
方法 #2:使用map()
+ concat
上述功能的组合也可以执行此任务。在此,我们使用 concat 执行扩展连接逻辑的任务,映射由 map() 完成。
# Python3 code to demonstrate working of
# Tuple String concatenation
# using map() + concat
from operator import concat
# initialize tuples
test_tup1 = ("Manjeet", "Nikhil", "Akshat")
test_tup2 = (" Singh", " Meherwal", " Garg")
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Tuple String concatenation
# using map() + concat
res = tuple(map(concat, test_tup1, test_tup2))
# printing result
print("The concatenated tuple : " + str(res))
输出 :
The original tuple 1 : ('Manjeet', 'Nikhil', 'Akshat')
The original tuple 2 : (' Singh', ' Meherwal', ' Garg')
The concatenated tuple : ('Manjeet Singh', 'Nikhil Meherwal', 'Akshat Garg')