![](/img/trans.png)
[英]Generate all possible combination with “N” length from given words list (Looking for no repeat)
[英]creating a list of all possible combination from a given list of words in python
我在创建给定单词列表的所有可能组合的列表时遇到问题。 结果应该是每行所有可能单词的组合。 组合的最大长度基于输入文件中给出的单词数量。 这意味着,如果文件包含 7 个单词,则组合最长为 7 个单词。 output 的格式应如下所示:
德国德国德国德国德国德国德国德国西班牙德国德国德国德国西班牙
等等等等
我用谷歌搜索了一下,发现 itertools 对我来说是一个可能的解决方案。
给定的单词位于名为 input.txt 的文件中
我在这里使用了堆栈溢出条目中的这段代码:
我只是将主要部分表示为文件读取部分,文件 output 不是这里问题的一部分。
所以我给出的单词列表是:德国西班牙阿尔巴尼亚荷兰
哪个工作正常
from itertools import combinations
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
output 与预期不符。
因为我的列表包含 3 个词,所以我更改了代码:
德国 西班牙 阿尔巴尼亚
哪个工作正常
from itertools import combinations
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
但是,我相信结果并不像预期的那样,它应该是所有可能的组合。 缺少一些组合,例如:
germany
germany germany
germany germany spain
germany germany germany
或者其他的东西。
(output 限制为 3,因为给定的列表在原始问题中包含 3 个单词)。
我如何将 germany germany 等组合获取到 output,为什么它们不见了? 我相信当我使用数字作为别针或其他东西时,我应该有同样的问题。 它不能从 0 到 9999 开始,但列表中也应该有 00、000 和 0000。
最好的问候弗雷德
我相信您想使用 function combinations_with_replacement :
from itertools import combinations_with_replacement
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations_with_replacement(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.