在 Python 中生成排列单词列表的子集
我有一个单词列表,我需要生成这些单词的所有可能的排列,但有一个警告。
我目前使用以下代码:
from itertools import permutations
wordlist = ["word1", "word2", "word3"]
for perm in permutations(wordlist):
print "".join(perm)
给出输出:
word1word2word3
word1word3word2
...
word3word2word1
但是我还需要它来打印这些单词的子集,例如:
word1
word1word2
word2word1
...
但我完全不知道如何做到这一点。 我从哪里开始呢?我应该读什么?
I have a list of words and I need to generate all possible permutations of these, with one caveat.
I currently use the following code:
from itertools import permutations
wordlist = ["word1", "word2", "word3"]
for perm in permutations(wordlist):
print "".join(perm)
which gives the output:
word1word2word3
word1word3word2
...
word3word2word1
However I also need it to print subsets these words, such as:
word1
word1word2
word2word1
...
But I haven't the slightest idea how to do this.
Where do I begin? What should I read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:
编辑: 输出:
Edited:
Edit: output:
这是一个更完整的文件 I/O 实现。
谢谢史蒂夫,我根据你的回答。
与其他帖子不同,此代码是为 Python 3.3.4 编写的
Here is a more complete implementation with file I/O.
Thanks Steve, I based myself on your answer.
This code, unlike other posts, was written for Python 3.3.4