繁体   English   中英

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

[英]Getting all possible combinations of any non-zero length from n lists

我有一个看起来像这样的列表:

[["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')]

您提到的工具可以结合使用:

>>> 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')

您可以这样做:

>>> 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']]

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

# 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']

暂无
暂无

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

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