📜  Python|列表列表中的列产品

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

Python|列表列表中的列产品

有时,我们会遇到这样的问题,我们需要找到矩阵中每一列的乘积,即列表列表中每个索引的乘积。这种问题在竞争性编程中非常常见和有用。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用循环 + 列表理解 + zip()
需要结合上述方法来解决这个特定问题。显式产品函数用于获取所需的产品值,zip函数提供相似索引的组合,然后使用列表推导创建列表。

# Python3 code to demonstrate
# Column Product in List of lists
# using loop + list comprehension + zip()
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= ele
    return res 
  
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop + list comprehension + zip()
# Column Product in List of lists
res = [prod(idx) for idx in zip(*test_list)]
  
# print result
print("The Product of each index list is : " + str(res))
输出 :
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]

方法 #2:使用map() + loop + zip()
这与上述方法的工作方式几乎相似,但不同之处在于我们使用 map函数来构建产品列表,而不是使用列表推导。

# Python3 code to demonstrate
# Column Product in List of lists
# using map() + loop + zip()
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= ele
    return res 
  
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using map() + loop + zip()
# Column Product in List of lists
res = list(map(prod, zip(*test_list)))
  
# print result
print("The Product of each index list is : " + str(res))
输出 :
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]