2013-10-15 80 views
2

我目前正在編寫一個使用itertools的程序,並且它的一部分似乎沒有正常運行。我希望確定排列函數輸出的列表長度的輸入等於它從中產生輸出的列表的長度。換句話說,我有Python Itertools排列

import itertools 

b = 0 
c = 9 
d = [0,1,2] 
e = len(d) 


while b < c: 
     d.append(b) 
     b = b+1 

print([x for x in itertools.permutations(d,e)]) 

而且我想這產生所有可能的排列等於這個長度的d。我一直在試驗這個,看起來第二個確定器必須是一個整數。我甚至嘗試過創建一個新的變量f,然後有f = int(e),然後在print語句中用f替換e,但沒有成功。我得到的這些都是[()]

感謝您的幫助。

+2

'[X for x in ...]'與'list(...)'相同 - 不需要列表理解。 –

+2

適合我...適合您的所有代碼?你有沒有嘗試過3而不是e? – sashkello

回答

4

您需要設置e之後您構建列表。 len(d)返回一個值,而不是對列表長度的引用。

d = range(0,9) # build an arbitrary list here 
       # this creates a list of numbers: [0,1,2,3,4,5,6,7,8] 
e = len(d) 
print list(itertools.permutations(d, e)) 

注意,置換的數量是非常大的,所以存儲所有的人都在列表中會消耗大量的內存 - 你會用這個更好:

d = range(0,9) 
e = len(d) 
for p in itertools.permutations(d, e): 
    print p