Python – 将矩阵转换为自定义元组矩阵
有时,在使用Python矩阵时,我们可能会遇到一个问题,即我们需要将Python矩阵转换为元组矩阵,该矩阵从外部列表中按行自定义附加值。这种问题可以在数据域中应用,因为 Matrix 是使用的积分 DS。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[4, 5], [7, 3]], add_list = [‘Gfg’, ‘best’]
Output : [(‘Gfg’, 4), (‘Gfg’, 5), (‘best’, 7), (‘best’, 3)]
Input : test_list = [[4, 5]], add_list = [‘Gfg’]
Output : [(‘Gfg’, 4), (‘Gfg’, 5)]
方法 #1:使用循环 + zip()
上述功能的组合可以用来解决这个问题。在此,我们使用 zip() 执行将自定义值绑定到行的每个元素的任务。这是执行此任务的蛮力方式。
# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing List elements
add_list = ['Gfg', 'is', 'best']
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
for e in ele:
res.append((idx, e))
# printing result
print("Matrix after conversion : " + str(res))
The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [(‘Gfg’, 4), (‘Gfg’, 5), (‘Gfg’, 6), (‘is’, 6), (‘is’, 7), (‘is’, 3), (‘best’, 1), (‘best’, 3), (‘best’, 4)]
方法 #2:使用列表理解 + zip()
这是可以执行此任务的另一种方式。在此,我们执行与上述方法类似的任务,只是作为速记。
# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing List elements
add_list = ['Gfg', 'is', 'best']
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
res = [(ele1, ele2) for ele1, sub in zip(add_list, test_list) for ele2 in sub]
# printing result
print("Matrix after conversion : " + str(res))
The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [(‘Gfg’, 4), (‘Gfg’, 5), (‘Gfg’, 6), (‘is’, 6), (‘is’, 7), (‘is’, 3), (‘best’, 1), (‘best’, 3), (‘best’, 4)]