简体   繁体   English

如何获得列表中所有列表组合的总和?

[英]how do I get the sum of combinations of all lists within lists?

I have a list of lists, and am trying to get the sum of all combinations.我有一个列表列表,并试图获得所有组合的总和。

For example: [[1,2,3],[2,3],[4,5]] would produce (1+2+4),(1+2+5),(1+3+4),(1+3+5), (2+2+4) etc.例如: [[1,2,3],[2,3],[4,5]]将产生(1+2+4),(1+2+5),(1+3+4),(1+3+5), (2+2+4)

I can't seem to find a way to do this- any help?我似乎找不到办法做到这一点 - 有什么帮助吗? Note that I know how to produce the sums, the issue is just with iterating over all combinations.请注意,我知道如何产生总和,问题只是迭代所有组合。

I had the idea of using zip() but this would sum everything in place, and then we could rotate the lists to cover all combinations, would this work?我有使用 zip() 的想法,但这会总结所有内容,然后我们可以旋转列表以涵盖所有组合,这可行吗? It seems very complicated.看起来很复杂。 Or is there a simpler way to iterate using a loop?或者有没有更简单的方法来使用循环进行迭代?

You could use itertools.product for that你可以使用itertools.product

lists = [[1, 2, 3], [2, 3], [4, 5]]
products = itertools.product(*lists)
for product in products:
    print(f'{product} {sum(product)}')

Output: 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

Easiest way is to use itertools.combinations .最简单的方法是使用itertools.combinations

Flatten the list of lists into just a list, and get all combinations by a generator.将列表列表展平为一个列表,并通过生成器获取所有组合。

Do whatever you want (sum) with each combination.对每种组合做任何你想做的事情(总和)。

from itertools import combinations

a = [[1,2,3],[2,3],[4,5]]
flat_a = [item for sublist in a for item in sublist]
for combination in combinations(flat_a, 3):
    print(f"{combination}, {sum(combination)}")

references:参考:

flatten 展平
combinations 组合

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM