📜  Python|元组列表中的最大产品对

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

Python|元组列表中的最大产品对

有时,在处理数据时,我们可能会遇到需要在列表中找到可用对之间的最大乘积的问题。这可以应用于数学领域的许多问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用max() + 列表推导
此功能的组合可用于执行此任务。在此,我们计算所有对的乘积,然后使用 max() 返回它的最大值。

# Python3 code to demonstrate working of
# Maximum of Product Pairs in Tuple List
# Using list comprehension + max()
  
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Maximum of Product Pairs in Tuple List
# Using list comprehension + max()
temp = [abs(b * a) for a, b in test_list]
res = max(temp)
  
# printing result
print("Maximum product among pairs : " + str(res))
输出 :
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Maximum product among pairs : 30

方法 #2:使用max() + lambda
这与上述方法类似。在这里,列表推导执行的任务是使用 lambda函数解决的,提供产品计算逻辑。返回最大值。产品对。

# Python3 code to demonstrate working of
# Maximum of Product Pairs in Tuple List
# Using lambda + max()
  
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Maximum of Product Pairs in Tuple List
# Using lambda + max()
res = max(test_list, key = lambda sub: sub[1] * sub[0])
  
# printing result
print("Maximum Product among pairs : " + str(res))
输出 :
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Maximum product among pairs : 30