简体   繁体   中英

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?

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', '&')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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