在 Python 中查找最大差异对
pythonserver side programmingprogramming更新于 2025/10/11 14:36:17
数据分析会带来各种挑战。在本文中,我们将以数字作为元素的列表。然后,我们将在列表中找到元素之间的值差异最大的元素对。
使用 nlargest
这里的方法是首先找出元素的所有可能组合,然后从第一个元素中减去第二个元素。最后应用 heapq 模块中的 nlargest 函数来获取差异最大的那些对。
示例
from itertools import combinations
from heapq import nlargest
listA = [21, 14, 30, 11, 17, 18]
# 给定列表
print("给定列表: ",listA)
# 使用 nlargest 和 combinations()
res = nlargest(2, combinations(listA, 2),
key=lambda sub: abs(sub[0] - sub[1]))
# 打印结果
print("Pairs with maximum difference are : ",res)
输出
运行上述代码得到以下结果 −
给定列表: [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : [(30, 11), (14, 30)]
使用 combinations 和 Max()
这里我们也采用与上面相同的方法,但我们得到一对结果,因为我们应用了 max 函数,该函数给出了一对结果。
示例
来自 itertools 导入 combinations
listA = [21, 14, 30, 11, 17, 18]
# 给定列表
print("给定列表: ",listA)
# 使用 combinations() 和 lambda
res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1]))
# 打印结果
print("Pairs with maximum difference are : ",res)
输出
运行上述代码得到以下结果 −
给定列表: [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : (30, 11)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

