📜  Python – 列表中的最大聚合对

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

Python – 列表中的最大聚合对

有时,我们需要找到获得最大和的对的具体问题,这可以通过在排序后获取初始两个元素来计算。但是在某些情况下,我们不需要更改列表的顺序并在类似列表中执行一些操作而不使用额外的空间。让我们讨论可以执行此操作的某些方式。

方法 #1:使用列表理解 + max() + combination() + lambda
可以使用上述函数的组合来执行此特定任务,其中我们使用列表推导来绑定所有功能,使用 max函数来获得最大和,组合函数在内部找到所有和,而 lambda函数用于计算总和。

# Python3 code to demonstrate 
# Maximum Aggretation Pair in List
# using list comprehension + max() + combinations() + lambda 
from itertools import combinations 
  
# initializing list 
test_list = [3, 4, 1, 7, 9, 1] 
  
# printing original list 
print("The original list : " + str(test_list)) 
  
# using list comprehension + max() + combinations() + lambda 
# Maximum Aggretation Pair in List
res = max(combinations(test_list, 2), key = lambda sub: sub[0] + sub[1]) 
  
# print result 
print("The maximum sum pair is : " + str(res)) 
输出 :
The original list : [3, 4, 1, 7, 9, 1]
The maximum sum pair is : (7, 9)

方法 #2:使用列表理解 + nlargest() + combination() + lambda
这种方法不仅可以找到单个最大值,还可以在需要时找到 k 个最大和对,并使用 nlargest函数而不是 max函数来实现此功能。

# Python3 code to demonstrate 
# Maximum Aggretation Pair in List
# using list comprehension + nlargest() + combinations() + lambda 
from itertools import combinations 
from heapq import nlargest
  
# initializing list 
test_list = [3, 4, 1, 7, 9, 8] 
  
# printing original list 
print("The original list : " + str(test_list)) 
  
# using list comprehension + nsmallest() + combinations() + lambda 
# Maximum Aggretation Pair in List
# computes 2 max sum pair 
res = nlargest(2, combinations(test_list, 2), key = lambda sub: sub[0] + sub[1]) 
  
# print result 
print("The maximum sum pair is : " + str(res))
输出 :
The original list : [3, 4, 1, 7, 9, 8]
The maximum sum pair is : [(9, 8), (7, 9)]