Python – 连接元组列表中的后部元素
给定元组列表,连接后部元素。
Input : test_list = [(1, 2, “Gfg”), (“Best”, )]
Output : Gfg Best
Explanation : Last elements are joined.
Input : test_list = [(1, 2, “Gfg”)]
Output : Gfg
Explanation : Last elements are joined.
方法 #1:使用列表理解 + join()
在此,我们使用“-1”作为索引检查最后一个元素,并使用 join() 执行连接,列表推导用于迭代每个元组。
Python3
# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using join() + list comprehension
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
# printing original list
print("The original list is : " + str(test_list))
# "-1" is used for access
res = " ".join([sub[-1] for sub in test_list])
# printing result
print("The Concatenated result : " + str(res))
Python3
# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using map() + itemgetter() + join()
from operator import itemgetter
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
# printing original list
print("The original list is : " + str(test_list))
# "-1" is used for access
# map() to get all elements
res = " ".join(list(map(itemgetter(-1), test_list)))
# printing result
print("The Concatenated result : " + str(res))
输出
The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best', )]
The Concatenated result : Gfg is Best
方法 #2:使用 map() + itemgetter() + join()
在此,我们使用 itemgetter(-1) 执行获取最后一个元素的任务,而 map() 用于获取所有最后一个元素,使用 join() 进行连接。
Python3
# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using map() + itemgetter() + join()
from operator import itemgetter
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
# printing original list
print("The original list is : " + str(test_list))
# "-1" is used for access
# map() to get all elements
res = " ".join(list(map(itemgetter(-1), test_list)))
# printing result
print("The Concatenated result : " + str(res))
输出
The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best', )]
The Concatenated result : Gfg is Best