📜  Python - 连接矩阵中的字符串行

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

Python - 连接矩阵中的字符串行

关于矩阵的问题在竞争性编程和数据科学领域都很常见。我们可能面临的一个这样的问题是在不均匀大小的矩阵中找到矩阵行的连接。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用join() + 列表推导
上述功能的组合可以帮助在一行中解决这个特定问题,因此非常有用。 join函数计算子列表的连接,并使用列表推导将所有这些绑定在一起。

# Python3 code to demonstrate
# Row String Concatenation Matrix
# using join() + list comprehension
  
# initializing list
test_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
  
# printing original list
print("The original list : " + str(test_list))
  
# using join() + list comprehension
# Row String Concatenation Matrix
res = [''.join(idx for idx in sub) for sub in test_list ]
  
# print result
print("The row concatenation in matrix : " + str(res))
输出 :
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']

方法#2:使用循环
此任务也可以以蛮力方式执行,我们只需迭代子列表并以蛮力方式执行连接,为每个子列表创建新字符串并附加到列表中。

# Python3 code to demonstrate
# Row String Concatenation Matrix
# using loop
  
# initializing list
test_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop
# Row String Concatenation Matrix
res = []
for sub in test_list:
    res_sub = ""
    for idx in sub:
        res_sub = res_sub + idx
    res.append(res_sub)
  
# print result
print("The row concatenation in matrix : " + str(res))
输出 :
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']