![](/img/trans.png)
[英]How can I find all combinations of numbers in a list that's equal to a certain value in python?
[英]Python: find all combinations of elements in list to reach a certain value
我得到了一个列表,例如: [2,5,8]
和一个值c
,例如 33。因此,因为列表的长度是3
,我必须返回一个元组列表(i,j,k)
其中i*w[0] + j*w[1] + k*w[2] == c (33)
。
当然,这很容易用3个for循环解决,如图:
res = []
for i in range(c+1):
for j in range(c+1):
for g in range(c+1):
if i*self.w[0] + j*self.w[1] + g*self.w[2] == c:
res.append((i,j,g))
return sorted(res)
output 将是:
[(0, 5, 1), (1, 3, 2), (2, 1, 3), (4, 5, 0), (5, 3, 1), (6, 1, 2), (9, 3, 0), (10, 1, 1), (14, 1, 0)]
问题是我也必须对其他长度的列表执行此操作。 所以我的问题是; 对于长度为x
(不太大)和给定值c
的列表,有谁知道通常如何做到这一点?
使用itertools.product
和operator.mul
:
>>> [k for k in product(range(c+1), repeat=len(w)) if sum(map(mul, w, k)) == c]
[(0, 5, 1), (1, 3, 2), (2, 1, 3), (4, 5, 0), (5, 3, 1), (6, 1, 2), (9, 3, 0), (10, 1, 1), (14, 1, 0)]
您可以使用itertools.product
和zip
在此处进行归纳:
import itertools
w = [3,1,2,5]
c = 33
l = [range(c + 1)] * len(w)
res = []
for values in itertools.product(*l):
if sum(a * b for a, b in zip(w, values)) == c:
res.append(values)
print(sorted(res))
如果需要,构建res
的循环可以替换为列表理解。 也就是说:
res = [values for values in itertools.product(*l)
if sum(a * b for a, b in zip(w, values)) == c]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.