📜  Python|元组的元素相乘

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

Python|元组的元素相乘

给定一个元组列表,任务是将元组的元素相乘并返回相乘元素的列表。

例子:

有多种方法可以将元组的元素相乘。让我们看看其中的几个。

# 方法一:使用迭代
这是实现此任务解决方案的最天真的方法。在此,我们遍历整个元组列表并将每个元组中的元素相乘以获得元素列表。

# Python code to convert list of tuple into list of elements
# formed by multiplying elements of tuple.
  
# Input list initialisation
Input = [(2, 3), (4, 5), (6, 7), (2, 8)]
  
# Output list initialisation
Output = []
  
# Iteration to multiply element and append multiplied element in 
# new list
for elem in Input:
    temp = elem[0]*elem[1]
    Output.append(temp)
  
# printing output
print("The original list of tuple is ")
print(Input)
  
print("\nThe answer is")
print(Output)

输出:

The original list of tuple is 
[(2, 3), (4, 5), (6, 7), (2, 8)]

The answer is
[6, 20, 42, 16]

# 方法2:使用列表推导
这是实现此任务解决方案的单线方法。

# Python code to convert list of tuple into list of elements
# formed by multiplying elements of tuple.
  
# Input list initialisation
Input = [(2, 3), (4, 5), (6, 7), (2, 8)]
  
# Iteration to multiply element and append multiplied element in 
# new list
Output = [(x * y) for x, y in Input]
  
# printing output
print("The original list of tuple is ")
print(Input)
  
print("\nThe answer is")
print(Output)

输出:

The original list of tuple is 
[(2, 3), (4, 5), (6, 7), (2, 8)]

The answer is
[6, 20, 42, 16]