📜  Python – 如何将元组中的所有项相乘

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

Python – 如何将元组中的所有项相乘

有时,在编程时,我们可能需要在元组元素之间执行乘积。这是一个必不可少的实用程序,因为我们多次遇到产品操作,并且元组是不可变的,因此需要处理。让我们讨论可以执行此任务的某些方式。

方法 #1:使用list() + 循环
可以组合上述功能来执行此任务。我们可以使用循环来累积乘积逻辑的结果。 list()函数用于执行相互转换。

# Python3 code to demonstrate working of 
# Tuple Elements Multiplication
# Using list() + loop
  
# getting Product 
def prod(val) : 
    res = 1 
    for ele in val: 
        res *= ele 
    return res  
  
# initializing tup 
test_tup = (7, 8, 9, 1, 10, 7) 
  
# printing original tuple 
print("The original tuple is : " + str(test_tup)) 
  
# Tuple Elements Multiplication 
# Using list() + loop
res = prod(list(test_tup)) 
  
# printing result 
print("The product of tuple elements are : " + str(res)) 
输出 :
The original tuple is : (7, 8, 9, 1, 10, 7)
The product of tuple elements are : 35280

方法 #2:使用map() + loop + list()
上述功能的组合可用于执行此任务。在此,我们首先将元组转换为列表,使用 map() 将每个列表元素展平,使用循环执行每个乘积,然后再次对结果列表的整体乘积使用循环。

# Python 3 code to demonstrate working of 
# Tuple Elements Multiplication
# Using map() + list() + loop
  
# getting Product 
def prod(val) : 
    res = 1 
    for ele in val: 
        res *= ele 
    return res  
  
# initializing tup 
test_tup = ([7, 8], [9, 1], [10, 7]) 
  
# printing original tuple 
print("The original tuple is : " + str(test_tup)) 
  
# Tuple Elements Multiplication
# Using map() + list() + loop 
res = prod(list(map(prod, list(test_tup)))) 
  
# printing result 
print("The product of tuple elements are : " + str(res)) 
输出 :
The original tuple is : (7, 8, 9, 1, 10, 7)
The product of tuple elements are : 35280