【问题标题】:Generate all possible combinations of characters, of every length, from an array using Python使用 Python 从数组中生成所有可能的字符组合,每个长度
【发布时间】: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 个字符.

【问题讨论】:

标签: python combinations


【解决方案1】:
from itertools import product

text = 'abc'

all_product = sum((list(product(text,repeat=i)) for i in range(len(text)+1)),[])
print(all_product)

输出:

[(), ('a',), ('b',), ('c',), ('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c'), ('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2021-12-14
    • 2016-02-07
    • 2012-08-23
    • 2023-03-26
    相关资源
    最近更新 更多