Reputation: 105
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.
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? It seems very complicated. Or is there a simpler way to iterate using a loop?
Upvotes: 1
Views: 139
Reputation: 27946
Easiest way is to use 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:
Upvotes: 0
Reputation: 62
from itertools import product
a = [[1,2,3],[2,3],[4,5]]
for i in product(a):
print(i," ",sum(i))
Upvotes: 0
Reputation: 50819
You could use itertools.product
for that
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
Upvotes: 1