📜  Python| List of Lists 中第 k 列的乘积

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

Python| List of Lists 中第 k 列的乘积

有时,在使用Python Matrix 时,我们可能会遇到需要查找特定列的乘积的问题。这可以在日间编程和竞争性编程中具有可能的应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + zip()
可以使用上述功能的组合来解决此任务。在此,我们传入 zip() 列表,以访问所有列和显式乘积函数以获取列的乘积。

# Python3 code to demonstrate working of
# Column Product in List of Lists
# using loop + zip()
  
# getting Product
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 K
K = 2
  
# Column Product in List of Lists
# using loop + zip()
res = [prod(idx) for idx in zip(*test_list)][K] 
  
# printing result
print("Product of Kth column is : " + str(res))
输出 :
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Kth column is : 56

方法#2:使用循环
这是解决此问题的蛮力方法。在此,我们遍历矩阵并通过测试列号来获取列的乘积。

# Python3 code to demonstrate working of
# Column Product in List of Lists
# 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 K
K = 2
  
# Column Product in List of Lists
# Using loop
res = 1
for sub in test_list:
    for idx in range(0, len(sub)):
        if idx == K:
            res = res * sub[idx]
  
# printing result
print("Product of Kth column is : " + str(res))
输出 :
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Kth column is : 56