2015-05-15 41 views
-3

我的代碼:Python的排列

a = [1,2,3] 
import itertools 
set(itertools.permutations(a)) 

我得到的輸出:

{(1, 3, 2), (3, 2, 1), (1, 2, 3), (2, 3, 1), (3, 1, 2), (2, 1, 3)} 

有人可以告訴我如何打印號碼,如:

123 
321 
132 
312 
213 
231 
+2

你嘗試過什麼嗎? – Totem

+0

就這麼你知道,你不需要一套。 –

+1

沒有太多的「如此」 - 三個項目有6個排列,所以當您打印其中的5個時,只有一個要添加。 – CiaPan

回答

4

基礎的在您的代碼上:

import itertools 

a=[1,2,3] 
permutations = set(itertools.permutations(a)) 

for perm in permutations: 
    print("%s%s%s" % perm) 

但是你並不需要使用set可言,因此該解決方案(實際上是一個更好的),可就是這樣過:

import itertools 

a=[1,2,3] 
for perm in itertools.permutations(a): 
    print("%s%s%s" % perm) 
+0

@ kunal51,你是否真的使用我的解決方案,因爲我發佈了它?如果你想做第一個想法,你需要將這個集合分配到'permutations'中。或者使用我發佈的第二個示例。無論如何,這是更好的。 – geckon

+0

@ kunal51它適用於我,你真的想要我貼什麼嗎? – geckon

+0

@ kunal51,現在有效嗎?你爲什麼要刪除你的評論? – geckon

1

鑄子元素爲字符串,然後加入他們的行列:

for perm in permutations: 
    print ''.join(map(str, perm))