2017-10-05 18 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'をインポートしますが、それを使用することはありません。代わりに、ほぼ同等のPythonコードをドキュメントからコピーしているように見えます。 –

+0

私はitertoolsをインポートする必要があると思ったので、ここで関数のソースコードを見つけました。https://docs.python.org/2/library/itertools.html –

+0

モジュールを使用してください! 'のようなitertools.combinations(samplelist、9)の櫛のように:print(comb) ' –

答えて

0

itertools.permutations(samplelist)は9を返します。リスト