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))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行上述代码将得到以下结果:

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)]

更新于:2020年8月26日

1K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告