简体   繁体   English

多个列表中的所有组合

[英]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. 我尝试使用itertools.product(* list),但这导致所有项目的组合没有较小的组合集。 It seems that itertools.combinations, itertools.permutations, etc don't quite give what I am looking for. 看来itertools.combinations,itertools.permutations等并没有完全满足我的要求。

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 : 对于每种长度,请选择列表的所有可能组合,对于每种组合,请使用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', '&')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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