所以我最近选择了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']
非常感谢任何帮助。
答案 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']