Skip to main content
 首页 » 编程设计

python之根据元组的总和获取元组元素的乘积

2025年05月04日24thcjp

对于以下问题的任何反馈,我将不胜感激。到目前为止,我在 Python 上编写了一个代码,它生成二维元组的组合,其中每个元素都是从 1 到 4 的值。因此对于 (a1,a2),a1 和 a2 可以是从 1 到 4 的任何值

因此这生成了以下元组

tuple_combinations =  [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)] 

然后我对生成的每个元组的元素求和:

sum_tuple_combinations = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8] 

现在我需要帮助来计算总和为 5 的元组的元素乘积。因此对于此示例,这将是元组 (2,3)、(3,2)、(1,4) 和(4,1) 这会给我

 [6,6,4,4] 

我如何在 Python 上编写代码?

这是我到目前为止所做的:

  import itertools 
  x = [1,2,3,4] 
  combinations= [p for p in itertools.product(x, repeat=2)] 
  print(combinations) 
  sum_of_combinations = map(sum, combinations) 
  print(sum_of_combinations) 
  #product_of_combinations = [x*y for sum_of_combinations = 5] 

此外,虽然这解决了二维情况,其中 n=2 ,但我想考虑其他维度的元组中元素的乘积,例如 n=200 等等。因此,特别是对于 N=200 这样的维度,我想知道是否有一种计算成本低廉的方法来实现这一点?

请您参考如下方法:

不要忘记 (1, 4) 和 (4, 1) 的和也是 5。

二维情况:

>>> from itertools import product 
>>> L = [1, 2, 3, 4] 
>>> [a*b for a,b in product(L, L) if a+b == 5] 
[4, 6, 6, 4] 

n-dim 情况:

>>> from operator import mul 
>>> n = 2 
>>> [reduce(mul, t, 1) for t in product(L, repeat=n) if sum(t) == 5] 
[4, 6, 6, 4]