2017-09-01 39 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']