[英]how do I get the sum of combinations of all lists within lists?
我有一个列表列表,并试图获得所有组合的总和。
例如: [[1,2,3],[2,3],[4,5]]
将产生(1+2+4),(1+2+5),(1+3+4),(1+3+5), (2+2+4)
等
我似乎找不到办法做到这一点 - 有什么帮助吗? 请注意,我知道如何产生总和,问题只是迭代所有组合。
我有使用 zip() 的想法,但这会总结所有内容,然后我们可以旋转列表以涵盖所有组合,这可行吗? 看起来很复杂。 或者有没有更简单的方法来使用循环进行迭代?
你可以使用itertools.product
lists = [[1, 2, 3], [2, 3], [4, 5]]
products = itertools.product(*lists)
for product in products:
print(f'{product} {sum(product)}')
Output:
(1, 2, 4) 7
(1, 2, 5) 8
(1, 3, 4) 8
(1, 3, 5) 9
(2, 2, 4) 8
(2, 2, 5) 9
(2, 3, 4) 9
(2, 3, 5) 10
(3, 2, 4) 9
(3, 2, 5) 10
(3, 3, 4) 10
(3, 3, 5) 11
from itertools import product
a = [[1,2,3],[2,3],[4,5]]
for i in product(a):
print(i," ",sum(i))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.