将itertools.permutations的输出从元组列表转换为字符串列表

时间:2013-04-28 16:07:41

标签: python string list tuples permutation

在使用itertools排列函数后,列表出现了一些问题。

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']

4 个答案:

答案 0 :(得分: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. 函数名称不代表它的作用。最长的一句话?

答案 1 :(得分:0)

Permutations返回一个迭代器,产生元组,因此你需要加入它们。地图是一种很好的方式,而不是你的for循环。

from itertools import permutations

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

longestWord("aah")  

你这样做的方式,你将每个元组中的字母加入一个字符串,但你没有改变组合列表。

答案 2 :(得分:0)

请改为尝试:

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

(你的join并没有真正做任何有用的事情 - 在执行连接后,它的返回值没有被保存。)

答案 3 :(得分:0)

一个班轮

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