Search code examples
pythoncombinationspython-itertools

Printing specific combinations


I have been working on a few combination programs, currently, what I want to do is technically accomplished by the below:

from itertools import combinations

item_1 = [1,2,3,4,5,6,8,7]
item_2 = [10,12,14,15,16,17,19]
item_3 = [21,22,23,27,25,29]
item_4 = [32,33,36,37,38,39]
item_5 = [42,43,45,46,47,49]
item_6 = [51,52,53,57,59]
item_7 = [61,62,68]
item_8 = [71,72,75,78,79]

all_lists = item_1 + item_2 + item_3 + item_4 + item_5 + item_6 + item_7 + item_8

for (a,b,c,d,e,f,g,h) in combinations(all_lists, 8):
    print((a,b,c,d,e,f,g,h))
OUTPUT:
(1, 2, 3, 22, 25, 32, 39, 45)
(1, 2, 3, 22, 25, 32, 39, 46)
(1, 2, 3, 22, 25, 32, 39, 47)
(1, 2, 3, 22, 25, 32, 39, 49)
(1, 2, 3, 22, 25, 32, 39, 51)
(1, 2, 3, 22, 25, 32, 39, 52)
(1, 2, 3, 22, 25, 32, 39, 53)
(1, 2, 3, 22, 25, 32, 39, 57)

However, I do not need to include overlapping items, for example:

item_1 = [1,2,3,4,5,6,8,7] should all stay in the 'a' variable
item_2 = [10,12,14,15,16,17,19] should all stay in the 'b' variable
item_3 = [21,22,23,27,25,29] should all stay in the 'c' variable

I am just trying to see all combinations, but keep each list in it's individual letter but right now it is going through the combination of all lists, as I add them together to make the combinations() function work.

Is there a way or another itertools function to accomplish what I am trying to achieve?


Solution

  • I think you're after product.

    from itertools import product
    
    item_1 = [1,2,3,4,5,6,8,7]
    item_2 = [10,12,14,15,16,17,19]
    item_3 = [21,22,23,27,25,29]
    item_4 = [32,33,36,37,38,39]
    item_5 = [42,43,45,46,47,49]
    item_6 = [51,52,53,57,59]
    item_7 = [61,62,68]
    item_8 = [71,72,75,78,79]
    
    all_lists = [item_1, item_2, item_3, item_4, item_5, item_6, item_7, item_8]
    
    for (a,b,c,d,e,f,g,h) in product(*all_lists):
        print((a,b,c,d,e,f,g,h))