2017-09-21 28 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