📜  Python|记录指数产品

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

Python|记录指数产品

有时,在处理记录时,我们可能会遇到一个问题,即我们需要将作为元组的列表容器的所有列相乘。这种应用程序在 Web 开发领域很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + 列表理解 + zip()
可以使用上述功能的组合来执行此任务。在此,我们累积相似的索引元素,即使用 zip() 的列,然后使用列表推导遍历它们并使用显式函数执行产品。

Python3
# Python3 code to demonstrate working of
# Record Index Product
# using list comprehension + loop + zip()
   
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
   
# initialize list
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
   
# printing original list
print("The original list : " + str(test_list))
   
# Record Index Product
# using list comprehension + loop + zip()
res = [prod(ele) for ele in zip(*test_list)]
   
# printing result
print("The Cumulative column product is : " + str(res))


Python3
# Python3 code to demonstrate working of
# Record Index Product
# using zip() + map() + loop
   
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
   
# initialize list
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
   
# printing original list
print("The original list : " + str(test_list))
   
# Record Index Product
# using zip() + map() + loop
res = list(map(prod, zip(*test_list)))
   
# printing result
print("The Cumulative column product is : " + str(res))


输出:

The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column product is : [6, 84, 144]

方法#2:使用 zip() + map() + loop
该方法与上述方法类似。在此,列表推导执行的任务由 map() 执行,它将列的乘积扩展到压缩元素。

Python3

# Python3 code to demonstrate working of
# Record Index Product
# using zip() + map() + loop
   
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
   
# initialize list
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
   
# printing original list
print("The original list : " + str(test_list))
   
# Record Index Product
# using zip() + map() + loop
res = list(map(prod, zip(*test_list)))
   
# printing result
print("The Cumulative column product is : " + str(res))

输出:

The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column product is : [6, 84, 144]