2017-10-05 1 views
1

목록의 모든 순열을 탐색해야합니다. 예 출력이 될 것목록 요소 내에서 가능한 모든 조합 만들기

samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

:의 난이 시작 변수가 있다고 가정 해 봅시다 여기

output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on. 

것은 내가 무슨 짓을했는지 :

import itertools 
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

def combinations(iterable, r): 

    pool = tuple(iterable) 
    n = len(pool) 
    if r > n: 
     return 
    indices = range(r) 
    yield tuple(pool[i] for i in indices) 
    while True: 
     for i in reversed(range(r)): 
      if indices[i] != i + n - r: 
       break 
     else: 
      return 
     indices[i] += 1 
     for j in range(i+1, r): 
      indices[j] = indices[j-1] + 1 
     yield tuple(pool[i] for i in indices) 

list(combinations_with_replacement(samplelist, 9)) 

리스트의 길이는 9이므로, 9의 팩토리얼은 362,880입니다. 목록에있는 요소의 모든 조합을 얻으려고합니다.

그러나 내 결과는 내가 성취하려는 것이 아닙니다.

+0

당신은'itertools'를 가져 오지 만 그것을 사용하지는 않습니다. 대신에 문서에서 대략적으로 동일한 파이썬 코드를 복사하고있는 것 같습니다. 왜 모듈을 사용하지 않을까요? –

+0

여기에 함수 소스 코드를 찾았으므로 itertools를 가져와야한다고 생각했습니다. https://docs.python.org/2/library/itertools.html –

+0

모듈을 사용하십시오! like itertools.combinations (samplelist, 9)의 빗용 : print (comb)' –

답변

0

itertools.permutations (samplelist)는 9를 반환합니다! 리스트