Python – 矩阵中的垂直串联
给定一个字符串矩阵,执行字符串的按列连接,处理可变列表长度。
Input : [[“Gfg”, “good”], [“is”, “for”]]
Output : [‘Gfgis’, ‘goodfor’]
Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on.
Input : [[“Gfg”, “good”, “geeks”], [“is”, “for”, “best”]]
Output : [‘Gfgis’, ‘goodfor’, “geeksbest”]
Explanation : Column wise concatenated Strings, “Gfg” concatenated with “is”, and so on.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代所有列并执行连接。
Python3
# Python3 code to demonstrate working of
# Vertical Concatenation in Matrix
# Using loop
# initializing lists
test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]
# printing original list
print("The original list : " + str(test_list))
# using loop for iteration
res = []
N = 0
while N != len(test_list):
temp = ''
for idx in test_list:
# checking for valid index / column
try: temp = temp + idx[N]
except IndexError: pass
res.append(temp)
N = N + 1
res = [ele for ele in res if ele]
# printing result
print("List after column Concatenation : " + str(res))
Python3
# Python3 code to demonstrate working of
# Vertical Concatenation in Matrix
# Using join() + list comprehension + zip_longest()
from itertools import zip_longest
# initializing lists
test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]
# printing original list
print("The original list : " + str(test_list))
# using join to concaternate, zip_longest filling values using
# "fill"
res = ["".join(ele) for ele in zip_longest(*test_list, fillvalue ="")]
# printing result
print("List after column Concatenation : " + str(res))
输出
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']
方法 #2:使用 join() + 列表理解 + zip_longest()
上述功能的组合可以用来解决这个问题。在此,我们使用 zip_longest 处理空索引值,并使用 join() 执行连接任务。列表理解驱动单行逻辑。
Python3
# Python3 code to demonstrate working of
# Vertical Concatenation in Matrix
# Using join() + list comprehension + zip_longest()
from itertools import zip_longest
# initializing lists
test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]
# printing original list
print("The original list : " + str(test_list))
# using join to concaternate, zip_longest filling values using
# "fill"
res = ["".join(ele) for ele in zip_longest(*test_list, fillvalue ="")]
# printing result
print("List after column Concatenation : " + str(res))
输出
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']]
List after column Concatenation : ['GfgisBest', 'goodfor']