Python|第 N 列矩阵乘积
有时,在使用Python Matrix 时,我们可能会遇到需要查找特定列的乘积的问题。这可以在日间编程和竞争性编程中具有可能的应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + zip()
可以使用上述功能的组合来解决此任务。在此,我们传入 zip() 列表,以访问所有列并循环获取列的乘积。
# Python3 code to demonstrate working of
# Nth column Matrix Product
# using loop + zip()
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# using loop + zip()
res = [prod(idx) for idx in zip(*test_list)][N]
# printing result
print("Product of Nth column is : " + str(res))
输出 :
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 56
方法#2:使用循环
这是解决此问题的蛮力方法。在此,我们遍历矩阵并通过测试列号来获取列的乘积。
# Python3 code to demonstrate working of
# Nth column Matrix Product
# Using loop
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# Using loop
res = 1
for sub in test_list:
for idx in range(0, len(sub)):
if idx == N:
res = res * sub[idx]
# printing result
print("Product of Nth column is : " + str(res))
输出 :
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 56