【发布时间】:2022-11-02 00:48:43
【问题描述】:
我想从数组["a", "b", "c"] 中生成所有可能的字母组合
我见过应该生成所有组合的程序,但我得到了[('a', 'b'), ('a', 'c'), ('b', 'c')],这是错误的,因为它缺少('b', 'a'), ('b', 'b') ('c', 'a'), ('c', 'b')。有谁知道如何生成全部的组合,而代码仍然很快?
我检查了其他问题关于这一点,但它们使用的是 Python 以外的不同语言,或者它们只是没有生成所有可能的组合.有些确实生成了所有组合,但带有数字和特定长度。我想所有的字符组合.
这是无法正常工作的代码(未生成所有组合):
import itertools
stuff = [1, 2, 3]
for L in range(len(stuff) + 1):
for subset in itertools.combinations(stuff, L):
print(subset)
这是另一个(也没有生成所有组合):
from itertools import chain, combinations
def all_subsets(ss):
return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))
for subset in all_subsets(stuff):
print(subset)
两个输出都是:
()
('a',)
('b',)
('c',)
('a', 'b')
('a', 'c')
('b', 'c')
('a', 'b', 'c')
不是所有的组合。
这就是我想要的:
()
('a',)
('b',)
('c',)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
('a', 'b', 'c')
...
每一种可能的组合。就好像您有一个只有 A B 和 C 键的键盘,而您正在尝试编写所有内容。如果您考虑一下,这意味着某些组合可以是('a','a','a','a','a','a')等等,所以让我们将最大长度设置为 30 个字符.
【问题讨论】:
-
我认为您正在寻找 [
permutations](docs.python.org/3/library/itertools.html#itertools.permutations) 而不是combinations。
标签: python combinations