Ripster Ripster -4 years ago 126
Python Question

All combinations across multiple lists

Given a multidimensional list (a list of lists) I would like to get all possible combinations of the sub lists items.

For example an input of:

my_list = [
['a', 'b'], ['1', '2'], ['@', '&']
]


Would result in:

result = [
['a'],
['b'],
['1'],
['2'],
['@'],
['&'],
['a', '1'],
['a', '2'],
['a', '@'],
['a', '&']
['b', '1'],
['b', '2'],
['b', '@'],
['b', '&'],
['a', '1', '@'],
['a', '1', '&'],
['a', '2', '@'],
['a', '2', '&'],
...]


I tried using itertools.product(*list) but that results in a combination of all items without the smaller sets of combinations. It seems that itertools.combinations, itertools.permutations, etc don't quite give what I am looking for.

Is there a quick way of doing this?

Answer Source

In that case you first iterate over all possible lengths. For each length you pick all possible combinations of lists, and for each of these combinations you use itertools.product:

def weird_product(*data):
    for i in range(1,len(data)+1):
        for subdata in itertools.combinations(data,i):
            for elem in itertools.product(*subdata):
                yield elem

This generates:

>>> list(weird_product(*data))
[('a',), ('b',), ('1',), ('2',), ('@',), ('&',), ('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'), ('a', '@'), ('a', '&'), ('b', '@'), ('b', '&'), ('1', '@'), ('1', '&'), ('2', '@'), ('2', '&'), ('a', '1', '@'), ('a', '1', '&'), ('a', '2', '@'), ('a', '2', '&'), ('b', '1', '@'), ('b', '1', '&'), ('b', '2', '@'), ('b', '2', '&')]

or more elegantly formatted:

>>> list(weird_product(*data))
[('a',),
 ('b',),
 ('1',),
 ('2',),
 ('@',),
 ('&',),
 ('a', '1'),
 ('a', '2'),
 ('b', '1'),
 ('b', '2'),
 ('a', '@'),
 ('a', '&'),
 ('b', '@'),
 ('b', '&'),
 ('1', '@'),
 ('1', '&'),
 ('2', '@'),
 ('2', '&'),
 ('a', '1', '@'),
 ('a', '1', '&'),
 ('a', '2', '@'),
 ('a', '2', '&'),
 ('b', '1', '@'),
 ('b', '1', '&'),
 ('b', '2', '@'),
 ('b', '2', '&')]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download