一起添加单词以形成所有可能的组合

时间:2017-01-10 18:15:18

标签: python iteration itertools

所以我最近选择了python,我试图获得多个单词的所有不同组合。我一直在看itertools,但未能达到我想要的结果。用实际例子更容易解释。这就是我想要实现的目标:

somestring = "cat, cake, apples"
result = itertools magik
print result

>>> catcake, catapples, cakecat, cakeapples, applescat, applescake

到目前为止,这是我最接近实现这一目标的方法,但它不会每次迭代都返回:

from itertools import combinations
print ["".join(a) for a in combinations(["cat", "cake", "apples"], 2)]

>>> ['catcake', 'catapples', 'cakeapples']

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这应该有效

from itertools import permutations
print ["".join(a) for a in permutations(["cat", "cake", "apples"], 2)]
#['catcake', 'catapples', 'cakecat', 'cakeapples', 'applescat', 'applescake']

这种情况发生是因为combinations命令并不重要,permutations确实很重要,例如:

'(cat,cake)' == '(cake, cat)' # Combinations
'(cat,cake)' != '(cake, cat)' # Permutations

答案 1 :(得分:1)

您实际上在寻找permutations而不是combinations

>>> print(["".join(a) for a in permutations(["cat", "cake", "apples"], 2)])
['catcake', 'catapples', 'cakecat', 'cakeapples', 'applescat', 'applescake']