2017-09-01 42 views
0

我有一个看起来像这样的列表:获取从n个非零长度的所有可能组合列出

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

回答

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