Python中查詢列表中和為給定值的全部三元組
在一個數字列表中,我們想要找出哪些三個元素可以組合成某個特定的和。我們稱之為三元組。在這個列表中可能存在許多這樣的三元組。例如,和10可以由數字1,6,3以及1,5,4生成。在本文中,我們將瞭解如何從給定的數字列表中找出所有這樣的三元組。
使用範圍和臨時變數
這是傳統方法,我們將建立臨時變數。這些變數將儲存列表中的元素,並檢查它們的和是否等於所需的值。然後它將不斷地將這些變數累積到最終的結果集中。
示例
def SumTriplets(listA, sum): trpltcnt = 0 res = [] for i in range(0, len(listA) - 1): s = set() tmp = [] # Adding first element tmp.append(listA[i]) current_sum = sum - listA[i] for j in range(i + 1, len(listA)): if (current_sum - listA[j]) in s: trpltcnt += 1 # Adding second element tmp.append(listA[j]) # Adding third element tmp.append(current_sum - listA[j]) # Appending tuple to the final list res.append(tuple(tmp)) tmp.pop(2) tmp.pop(1) s.add(listA[j]) return res listA = [11,12,13,14,15,16,17,18,19,20] print("Required triplets:\n",SumTriplets(listA, 40))
輸出
執行上述程式碼將得到以下結果:
Required triplets: [(11, 15, 14), (11, 16, 13), (11, 17, 12), (12, 15, 13)]
示例
from itertools import combinations listA = [11,12,13,14,15,16,17,18,19,20] def fsum(val): return sum(val) == 40 res = list(filter(fsum,list(combinations(listA, 3)))) print("Required triplets:\n",res)
輸出
執行上述程式碼將得到以下結果:
Required triplets: [(11, 12, 17), (11, 13, 16), (11, 14, 15), (12, 13, 15)]
廣告