在Python中生成排列单词列表的子集

5 投票
2 回答
2755 浏览
提问于 2025-04-16 08:26

我有一组单词,我需要生成这些单词的所有可能排列,但有一个条件。

我现在使用以下代码:

from itertools import permutations

wordlist = ["word1", "word2", "word3"]

for perm in permutations(wordlist):
    print "".join(perm)

这段代码的输出是:

word1word2word3
word1word3word2
...
word3word2word1

不过,我还需要它能打印出这些单词的子集,比如:

word1    
word1word2
word2word1
...

但是我完全不知道该怎么做。我要从哪里开始呢?我应该读些什么?

2 个回答

0

这里有一个更完整的实现,包含了文件输入输出的功能。感谢Steve,我是根据你的回答来写的。这个代码和其他帖子不同,是为Python 3.3.4版本编写的。

from itertools import permutations
import os

# GET FILE
script_dir = os.path.dirname(os.path.realpath(__file__))
wordlist_rel_path = "wordlist.txt"
wordlist_abs_file_path = os.path.join(script_dir, wordlist_rel_path)

# READ WORD LIST FROM FILE
word_list = []
print ("\ninput file is:", wordlist_abs_file_path,"\n")
with open(wordlist_abs_file_path) as wordlist:
     for line in wordlist:
         word_list.append(line.rstrip())

# PRINT INPUT LIST
print ("input list contains:")
print(word_list,"\n")

# GENERATE POWERSET
powerset_list = []
print ("output list is:")
for n in range(1, len(word_list)+1):
     for perm in permutations(word_list, n):
         powerset_list.append( "".join(perm) )
print(powerset_list)

# WRITE LIST TO FILE
powerset_rel_path = "powerset.txt"
powerset_abs_file_path = os.path.join(script_dir, powerset_rel_path)
powerset_abs_file = open(powerset_abs_file_path, 'w')
for item in powerset_list:
     powerset_abs_file.write("%s\n" % item)
powerset_abs_file.close()
6

编辑:

from itertools import permutations

xlist = ["word1", "word2", "word3"]

for n in range(1, len(xlist)+1):
    for perm in permutations(xlist, n):
        print "".join(perm)

编辑:输出:

word1
word2
word3
word1word2
word1word3
word2word1
word2word3
word3word1
word3word2
word1word2word3
word1word3word2
word2word1word3
word2word3word1
word3word1word2
word3word2word1

撰写回答