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

변수의 이름을 li로 지정하지 마십시오. 당신이'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