📜  Python – 连接元组中的连续元素

📅  最后修改于: 2022-05-13 01:54:57.638000             🧑  作者: Mango

Python – 连接元组中的连续元素

有时,在处理数据时,我们可能会遇到需要找到累积结果的问题。这可以是任何类型、乘积或总和。在这里,我们将讨论相邻元素连接。让我们讨论可以执行此任务的某些方式。

方法 #1:使用zip() + generator expression + tuple()
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式来提供连接逻辑,同时元素配对由 zip() 完成。使用 tuple() 将结果转换为元组形式。

# Python3 code to demonstrate working of
# Consecutive element concatenation in Tuple
# using zip() + generator expression + tuple
  
# initialize tuple
test_tup = ("GFG ", "IS ", "BEST ", "FOR ", "ALL ", "GEEKS")
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Consecutive element concatenation in Tuple
# using zip() + generator expression + tuple
res = tuple(i + j for i, j in zip(test_tup, test_tup[1:]))
  
# printing result
print("Resultant tuple after consecutive concatenation : " + str(res))
输出 :
The original tuple : ('GFG ', 'IS ', 'BEST ', 'FOR ', 'ALL ', 'GEEKS')
Resultant tuple after consecutive concatenation : ('GFG IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL GEEKS')

方法 #2:使用tuple() + map() + lambda
上述功能的组合也可以帮助执行此任务。在此,我们使用 lambda函数执行连接和绑定逻辑。 map() 用于迭代每个元素,最终结果由 tuple() 转换。

# Python3 code to demonstrate working of
# Consecutive element concatenation in Tuple
# using tuple() + map() + lambda
  
# initialize tuple
test_tup = ("GFG ", "IS ", "BEST ", "FOR ", "ALL ", "GEEKS")
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Consecutive element concatenation in Tuple
# using tuple() + map() + lambda
res = tuple(map(lambda i, j : i + j, test_tup[: -1], test_tup[1: ]))
  
# printing result
print("Resultant tuple after consecutive concatenation : " + str(res))
输出 :
The original tuple : ('GFG ', 'IS ', 'BEST ', 'FOR ', 'ALL ', 'GEEKS')
Resultant tuple after consecutive concatenation : ('GFG IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL GEEKS')