2013-04-28 145 views
5

在使用itertools permutations函數後列表中存在一些問題。將itertools.permutations的輸出從元組列表轉換爲字符串列表

from itertools import permutations 

def longestWord(letters): 
    combinations = list(permutations(letters)) 
    for s in combinations: 
     ''.join(s) 
    print(combinations) 

longestWord("aah") 

輸出看起來是這樣的:

[('a', 'a', 'h'), ('a', 'h', 'a'), ('a', 'a', 'h'), ('a', 'h', 'a'), 
('h', 'a', 'a'), ('h', 'a', 'a')] 

我想這是一個簡單的列表,但它似乎現身元組的列表(?)。任何人都可以幫我格式化它,所以它出現如下:

['aah', 'aha', 'aah', 'aha', 'haa', 'haa'] 
+2

調用排列'combinations'是混亂的。 – DSM 2013-04-28 16:58:52

回答

8
from itertools import permutations 

def longestWord(letters): 
    return [''.join(i) for i in permutations(letters)] 

print(longestWord("aah")) 

結果:

['aah', 'aha', 'aah', 'aha', 'haa', 'haa'] 

幾點建議:

  1. 不要在函數內部打印,而是返回並打印返回的值。
  2. 你的變量combination的命名並不好,因爲組合是由排列不同
  3. 您的加入並沒有做任何事情,加入不改變價值內聯,則返回字符串
  4. 的功能名稱並不代表它能做什麼。最長的單詞?
0

排列返回一個迭代器產生元組,所以你需要加入它們。地圖是一個很好的方式來代替你的for循環。

from itertools import permutations 

def longestWord(letters): 
    combinations = list(map("".join, permutations(letters))) 
    print(combinations) 

longestWord("aah") 

你這樣做的方式,你將每個元組中的字母加入到一個字符串中,但你並沒有改變組合列表。

0

試試這個:

combinations = permutations(letters) 
print [''.join(x) for x in combinations] 

(您join是不是真的做任何有用的事情 - 未保存加入進行它的返回值後)

+0

這裏的'list'不會給你帶來任何收益 – Eric 2013-04-28 16:37:45

+0

是的,從OP複製那條線用於上下文。 – 2013-04-28 18:33:38

0

一個襯墊

[''.join(h) for h in [list(k) for k in longestWord("aah")]]