在 Python 中查詢最大差值對
資料分析可能會帶來各種挑戰。在本文中,我們將使用一個以數字為元素的列表。然後,我們將在列表中找出值差最大的元素對。
使用 nlargest
這裡的方法是先找出所有可能的元素組合,然後從第一個元素中減去第二個元素。最後,應用 heapq 模組中的 nlargest 函式,以獲得差值最大的那些對。
示例
from itertools import combinations
from heapq import nlargest
listA = [21, 14, 30, 11, 17, 18]
# Given list
print("Given list : ",listA)
# using nlargest and combinations()
res = nlargest(2, combinations(listA, 2),
key=lambda sub: abs(sub[0] - sub[1]))
# print result
print("Pairs with maximum difference are : ",res)
輸出
執行上面的程式碼,我們得到以下結果 -
Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : [(30, 11), (14, 30)]
使用組合和 Max()
這裡我們也採取了與上面相同的方法,但我們得到一對作為結果,因為我們應用了 max 函式,它給我們一對作為結果。
示例
from itertools import combinations
listA = [21, 14, 30, 11, 17, 18]
# Given list
print("Given list : ",listA)
# using combinations() and lambda
res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1]))
# print result
print("Pairs with maximum difference are : ",res)輸出
執行上面的程式碼,我們得到以下結果 -
Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : (30, 11)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP