Python - 按行连接两个列表列表
给定两个矩阵,任务是编写一个Python程序,从初始矩阵向每一行添加元素。
Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
Output : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation : Matrix is row wise merged.
Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1], [9], [8]]
Output : [[4, 3, 5, 1], [1, 2, 3, 9], [3, 7, 4, 8]]
Explanation : Matrix is row wise merged.
方法 #1:使用enumerate() +循环
在这里,我们获取每个初始矩阵的每个索引并将其所有元素附加到第二个矩阵的相应行。
Python3
# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
# Using loop + enumerate()
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
for idx, ele in enumerate(test_list1):
new_vals = []
# getting all values at same index row
for ele in test_list2[idx]:
new_vals.append(ele)
# extending the initial matrix
test_list1[idx].extend(new_vals)
# printing result
print("The concatenated Matrix : " + str(test_list1))
Python3
# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
# Using zip() + list comprehension
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# zip() combines the results
# list comprehension provides shorthand
res = list(sub1 + sub2 for sub1, sub2 in zip(test_list1, test_list2))
# printing result
print("The concatenated Matrix : " + str(res))
输出:
The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]
The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]
The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
方法 #2:使用zip() +列表理解
在这里,我们使用 zip() 执行连接行的任务,并且使用列表理解对每一行进行迭代。
蟒蛇3
# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
# Using zip() + list comprehension
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# zip() combines the results
# list comprehension provides shorthand
res = list(sub1 + sub2 for sub1, sub2 in zip(test_list1, test_list2))
# printing result
print("The concatenated Matrix : " + str(res))
输出:
The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]
The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]
The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]