在 Python 中查找给定总和的列表中的所有三元组
pythonserver side programmingprogramming更新于 2025/10/11 9:48:17
在数字列表中,我们想要找出哪三个元素可以合并成一个特定的总和。我们称之为三元组。列表中可以有许多这样的三元组。例如,总和 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)]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

