📜  Python|元组列表交叉乘法

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

Python|元组列表交叉乘法

有时,在处理Python记录时,我们可能会遇到需要执行元组列表的交叉乘法的问题。这种应用程序在Web开发领域很流行。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + zip()
上述功能的组合可用于执行此特定任务。在此,我们使用列表推导遍历列表,并在 zip() 的帮助下执行跨列表的乘法。

# Python3 code to demonstrate working of
# Tuple list cross multiplication
# using list comprehension + zip()
  
# initialize lists
test_list1 = [(2, 4), (6, 7), (5, 1)]
test_list2 = [(5, 4), (8, 10), (8, 14)]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Tuple list cross multiplication
# using list comprehension + zip()
res = [(x[0] * y[0], x[1] * y[1]) for x, y in zip(test_list1, test_list2)]
  
# printing result
print("The multiplication across lists is : " + str(res))
输出 :
The original list 1 : [(2, 4), (6, 7), (5, 1)]
The original list 2 : [(5, 4), (8, 10), (8, 14)]
The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]

方法 #2:使用循环 + zip() + map()
这是执行此任务的另一种方式。这与上述方法类似,不同之处在于乘法是由显式函数执行的,而对每个元素的逻辑扩展是由 map() 完成的。

# Python3 code to demonstrate working of
# Tuple list cross multiplication
# using max() + zip() + loop
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= ele
    return res 
  
# initialize lists
test_list1 = [(2, 4), (6, 7), (5, 1)]
test_list2 = [(5, 4), (8, 10), (8, 14)]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Tuple list cross multiplication
# using max() + zip() + loop
res = [tuple(map(prod, zip(a, b))) for a, b in zip(test_list1, test_list2)]
  
# printing result
print("The multiplication across lists is : " + str(res))
输出 :
The original list 1 : [(2, 4), (6, 7), (5, 1)]
The original list 2 : [(5, 4), (8, 10), (8, 14)]
The multiplication across lists is : [(10, 16), (48, 70), (40, 14)]