从n个列表中获取任何非零长度的所有可能组合

时间:2017-09-01 12:28:53

标签: python arrays python-2.7 list

我有一个如下所示的列表:

[["0"], ["1", "2"], ["4"]]

我希望获得所有可能的排列,其中非零长度不超过此列表中每个列表的一个元素,甚至只是排列的数量。所以上面列表的结果将是:

[["0"], ["1"], ["2"], ["4"], ["0", "1"], ["0", "2"], ["1", "4"], ["2", "4"], ["0", "4"], ["0", "1", "4"], ["0", "2", "4"]]

子列表中的元素都是字符串。

我尝试过使用itertools.products但它只返回使用所有子列表的结果。

>>> import itertools
>>> l = [["0"], ["1", "2"], ["4"]]
>>> list(itertools.product(*l))
[('0', '1', '4'), ('0', '2', '4')]

3 个答案:

答案 0 :(得分:4)

您提到的工具组合起作用:

>>> from itertools import product, combinations
>>> l = [["0"], ["1", "2", "4"], ["8", "9"]]
>>> for lngth in range(1, len(l)+1):
...   for c in combinations(l, lngth):
...     for p in product(*c):
...       print(p)

('0',)
('1',)
('2',)
('4',)
('8',)
('9',)
('0', '1')
('0', '2')
('0', '4')
('0', '8')
('0', '9')
('1', '8')
('1', '9')
('2', '8')
('2', '9')
('4', '8')
('4', '9')
('0', '1', '8')
('0', '1', '9')
('0', '2', '8')
('0', '2', '9')
('0', '4', '8')
('0', '4', '9')

答案 1 :(得分:2)

你可以这样做:

>>> from itertools import product
>>> lst = [["0"], ["1", "2", "4", "6"]]
>>> result = [list(xi) for xi in sum(lst, []) + list(product(*lst))]
[['0'],
 ['1'],
 ['2'],
 ['4'],
 ['6'],
 ['0', '1'],
 ['0', '2'],
 ['0', '4'],
 ['0', '6']]

答案 2 :(得分:0)

对于那些喜欢自己动手的人:

# Yield all combinations of at most 1 element from each list in list_of_lists
# allowEmpty = "Allow an empty list to be one of the combinations"
def mixup( list_of_lists, allowEmpty=False ):
    if len(list_of_lists) == 0:
        if allowEmpty:
            yield []
    else:
        for x in mixup( list_of_lists[1:], True ):
            # x is some combination of remaining lists 
            if x!=[] or allowEmpty:
                # Result w/o contribution of 1st list
                yield x
            for h in list_of_lists[0]:
                # Result w/ contribution of 1st list
                yield [h]+x

那样

for x in mixup( [["0"], ["1", "2"], ["4", "6"]]  ):
    print x    

产量

['0']
['1']
['0', '1']
['2']
['0', '2']
['4']
['0', '4']
['1', '4']
['0', '1', '4']
['2', '4']
['0', '2', '4']
['6']
['0', '6']
['1', '6']
['0', '1', '6']
['2', '6']
['0', '2', '6']