Python|矩阵元组对列积
有时,我们会遇到一个问题,即我们处理复杂类型的矩阵列积,其中给定一个元组,我们需要执行其相似元素的乘积。这在机器学习领域有很好的应用。让我们讨论一些可以做到这一点的方法。
方法 #1:使用zip()
+ 列表理解
这个问题可以使用可以执行列产品逻辑的列表推导来解决,并且使用 zip函数来绑定元素,结果也是在垂直产品的时候。
# Python3 code to demonstrate
# Matrix Tuple pair Column product
# using list comprehension + zip()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + zip()
# Matrix Tuple pair Column product
res = [tuple(prod(j) for j in zip(*i)) for i in zip(*test_list)]
# print result
print("The product of columns of tuple list : " + str(res))
输出 :
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
The product of columns of tuple list : [(3, 28), (2, 27), (50, 10)]
方法 #2:使用zip() + map()
绑定列元素的任务也可以使用 map函数执行,而 zip函数执行绑定乘积元组的任务。两种逻辑都受列表理解的约束。
# Python3 code to demonstrate
# Matrix Tuple pair Column product
# using zip() + map()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
# printing original list
print("The original list : " + str(test_list))
# using zip() + map()
# Matrix Tuple pair Column product
res = [tuple(map(prod, zip(*i))) for i in zip(*test_list)]
# print result
print("The product of columns of tuple list : " + str(res))
输出 :
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]]
The product of columns of tuple list : [(3, 28), (2, 27), (50, 10)]