2017-10-05 103 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!列表