2015-06-29 65 views
4

所有可能的有序組給定的整數的有序列表:查找列表

[1,3,7,8,9] 

我如何才能找到其中爲了維持可從原來的列表中創建的所有子列表?使用上面的例子,我正在尋找一種方法以編程方式產生這些序列:

[[1],[3,7,8,9]] 
[[1, 3],[7,8,9]] 
[[1, 3, 7],[8,9]] 
[[1, 3, 7, 8],[9]] 
[[1, 3, 7, 8, 9]] 
[[1, 3, 7], [8, 9]] 
[[1], [3, 7], [8], [9]] 
[[1], [3], [7, 8], [9]] 
[[1], [3], [7], [8, 9]] 
... 

基本上,我在尋找一種方式來生成,其中爲了保持一個列表的所有排列。我可以生成所有那裏只有2總共子列表使用此代碼的子列表:

def partition(arr, idx): 
    return [arr[:idx], arr[idx:]] 

l = [1,3,7,8,9] 
for idx in range(1, len(l)): 
    groups = partition(l, idx) 
    print(groups) 

[[1], [3, 7, 8, 9]] 
[[1, 3], [7, 8, 9]] 
[[1, 3, 7], [8, 9]] 
[[1, 3, 7, 8], [9]] 

然而,這個代碼片段只分爲二的原始名單,併產生所有的地方只有兩個子列表可能的子列表。我怎樣才能生成所有可以從原始列表中創建的可以創建的子列表?

回答

8

如何:

import itertools 

def subsets(seq): 
    for mask in itertools.product([False, True], repeat=len(seq)): 
     yield [item for x, item in zip(mask, seq) if x] 

def ordered_groups(seq): 
    for indices in subsets(range(1, len(seq))): 
     indices = [0] + indices + [len(seq)] 
     yield [seq[a:b] for a,b in zip(indices, indices[1:])] 

for group in ordered_groups([1,3,7,8,9]): 
    print group 

結果:

[[1, 3, 7, 8, 9]] 
[[1, 3, 7, 8], [9]] 
[[1, 3, 7], [8, 9]] 
[[1, 3, 7], [8], [9]] 
[[1, 3], [7, 8, 9]] 
[[1, 3], [7, 8], [9]] 
[[1, 3], [7], [8, 9]] 
[[1, 3], [7], [8], [9]] 
[[1], [3, 7, 8, 9]] 
[[1], [3, 7, 8], [9]] 
[[1], [3, 7], [8, 9]] 
[[1], [3, 7], [8], [9]] 
[[1], [3], [7, 8, 9]] 
[[1], [3], [7, 8], [9]] 
[[1], [3], [7], [8, 9]] 
[[1], [3], [7], [8], [9]] 
+0

好像你正在重新塑造與'subsets'輪。我確信使用['itertools.combinations'](https://docs.python.org/3/library/itertools.html#itertools.combinations)可以更輕鬆地完成同樣的事情。 – Dunes

+0

我想你可以在範圍(len(seq)+1)中將'subsets'定義爲':for itertools.combinations(seq,i)中的x:yield list(x)'。不知道你是否可以只用一個'for'循環來完成。 – Kevin

+0

'[item for zip,zip(mask,seq)]如果x]' - >'list(itertools.compress(seq,mask))' – Navith