Home > database >  How to get all possible combinations from python list of tuples
How to get all possible combinations from python list of tuples

Time:01-10

I have a list like this..

[
    [
        ("a", 1)
    ] ,
    [
        ("b", 2)
    ],
    [
        ("c", 3),
        ("d", 4)
    ],
    [
        ("e", 5),
        ("f", 6),
        ("g", 7)
    ]
    
]

I am trying to get all possible combinations from this list data.

my expected output should look like below.

[
    [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("e", 5)
    ],
        [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("f", 6)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("g", 7)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("e", 5)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("f", 6)
    ],
    [
        ("a", 1),
        ("b", 2),
        ("d", 4),
        ("g", 7)
    ],
]

I tried with itertools.combinations but I am unable to get my expected output not sure what I am missing, unable to find the logic, kindly help. Thanks in advance.

Please let me know if you need any additional info,

thanks in advance,

CodePudding user response:

You want itertools.product, not itertools.combinations. Each list of tuples should be one argument to product, so use the * operator to pass each element of your starting list as an argument:

>>> import itertools
>>> list(itertools.product(*lists_of_tuples))
[(('a', 1), ('b', 2), ('c', 3), ('e', 5)), (('a', 1), ('b', 2), ('c', 3), ('f', 6)), (('a', 1), ('b', 2), ('c', 3), ('g', 7)), (('a', 1), ('b', 2), ('d', 4), ('e', 5)), (('a', 1), ('b', 2), ('d', 4), ('f', 6)), (('a', 1), ('b', 2), ('d', 4), ('g', 7))]

CodePudding user response:

if you really want to use combinations, and get the output format shown, you could do something like

from itertools import combinations

input_list = [
    [("a", 1)],
    [("b", 2)],
    [("c", 3), ("d", 4)],
    [("e", 5), ("f", 6), ("g", 7)],
]

list_for_combos = [i[n] for i in input_list for n, _ in enumerate(i)]

combos = list(
    [combo[n] for n, _ in enumerate(combo)]
    for combo in combinations(list_for_combos, 4)
)

CodePudding user response:

I think itertools.products() should work
also as you want the result as a 2d list this should work fine.

[list(x) for x in itertools.product(*li)]  # li is your list
  •  Tags:  
  • Related