Python – 字符串矩阵连接
有时,在使用 Matrix 时,我们可能会遇到一个问题,即我们有字符串,我们需要对其中存在的所有字符串进行通用连接。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + join()
我们可以使用列表推导来解决这个问题,作为我们可以用来执行这个特定任务的传统循环的潜在速记。我们只需将提取的元素连接起来,并将它们作为单个字符串放入 a 中。
# Python3 code to demonstrate
# String Matrix Concatenation
# Using list comprehension
# initializing list
test_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension
# count of all the elements in list
res = "".join([ele for sub in test_list for ele in sub])
# print result
print("The Matrix Concatenation is : " + str(res))
输出 :
The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]
The Matrix Concatenation is : geeksforgeeks is best I Love Gfg
方法#2:使用chain() + join()
这个特殊问题也可以使用链函数来解决,而不是使用传统的连接函数来连接的列表推导。
# Python3 code to demonstrate
# String Matrix Concatenation
# Using chain() + join()
from itertools import chain
# initializing list
test_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]]
# printing original list
print("The original list : " + str(test_list))
# using chain() + join()
# String Matrix Concatenation
res = "".join(list(chain(*test_list)))
# print result
print("The Matrix Concatenation is : " + str(res))
输出 :
The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]
The Matrix Concatenation is : geeksforgeeks is best I Love Gfg