2017-09-21 30 views
2

有很多問題都是相關的,但沒有一個我可以找到我正在尋找的東西。從本質上講,我希望將所有可能組合的每個子列表的所有排列組合在一起,但要保持它們分開。因此:列表內和列表之間的排列[python]

input=[[1,2,3],[4],[5,6]] 

所需的輸出:

[[1,2,3],[4],[6,5]] 

[[2,1,3],[4],[5,6]] 

[[2,1,3],[4],[5,6]] 

[[3,1,2],[4],[5,6]] 

等等

我相信下面的代碼的工作,但我不知道是否有任何更有效或簡潔策略。非常感謝你。

input=[[1,2,3],[4],[5,6]] 
all_lists=[] 

for i in xrange(len(input)): 
    all_lists.append(list(itertools.permutations(input[i]))) 

all_combinations = list(itertools.product(*all_lists)) 

## concat them together 
combinations_combined = [list(itertools.chain(*a)) for a in all_combinations] 
+2

不要將變量命名爲li ke'input',你重載對'input'內建的引用。 –

+0

我不在我的代碼中 - 這只是爲了舉例。我也不會在這裏做。 – ben

回答

2

我們可以先用列表解析生成每個子列表所有排列:

perms = [list(map(list,permutations(subl))) for subl in data] 

,然後我們可以使用product來獲得產品。

for data in product(*perms): 
    print(list(data)) 

或全部:

from itertools import permutations, product 

def product_perms(data): 
    perms = [list(map(list,permutations(subl))) for subl in data] 
    for data in product(*perms): 
     print(list(data)) 

這將產生:

>>> product_perms(data) 
[[1, 2, 3], [4], [5, 6]] 
[[1, 2, 3], [4], [6, 5]] 
[[1, 3, 2], [4], [5, 6]] 
[[1, 3, 2], [4], [6, 5]] 
[[2, 1, 3], [4], [5, 6]] 
[[2, 1, 3], [4], [6, 5]] 
[[2, 3, 1], [4], [5, 6]] 
[[2, 3, 1], [4], [6, 5]] 
[[3, 1, 2], [4], [5, 6]] 
[[3, 1, 2], [4], [6, 5]] 
[[3, 2, 1], [4], [5, 6]] 
[[3, 2, 1], [4], [6, 5]] 

如果你想這樣的列表,你可以使用:

def product_perms(data): 
    perms = [list(map(list,permutations(subl))) for subl in data] 
    return [list(data) for data in product(*perms)] 
+0

這太棒了!非常感謝你! – ben