2017-09-21 4 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]] 

等...

私は、次のコードが動作すると信じていますが、任意のより効率的か、簡潔な戦略があった場合、私は思っていました。どうもありがとうございました。

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

をし、我々は製品を得るためにproductを使用することができます。

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

変数に名前を付けない'input'の組み込み関数への参照を上書きします。 –

+0

私は自分のコードではありません - これは例のためのものです。私はここでもやっています。 – ben

答えて

2

まず、各サブリストについてすべての順列を生成するために、リスト内包を使用することができます。

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

関連する問題