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

9
使用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']

3
将排列称为"组合"会令人感到困惑。 - DSM
4个回答

11
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 不好,因为组合(combination)与排列(permutation)不同。
  3. 您的连接(join)没有做任何事情,连接不会改变值,它返回字符串。
  4. 函数名称不能代表其实际功能。最长的单词?

2

排列函数返回一个迭代器,它会产生元组,因此你需要将它们连接起来。使用映射函数是一种不错的方式,可以替代你的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并没有做任何有用的事情 - 在执行完join之后,它的返回值并没有被保存。


这里的 list 没有任何用处。 - Eric
是的,为了上下文,我从OP那里复制了那行代码。 - ron rothman

0

一行代码

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接