从 python 中的输入生成组合

Generate combinations from an input in python

我不确定如何在 Python 中解决这个问题。在搜索时,我遇到了 itertools,但我不确定在这种情况下如何应用它。

我想做的是创建一个脚本,该脚本可以接受包含查询标记(如 AB?D?)和一组选项(ABC、DEF)的字符串输入,以输出所有可能的组合,如下面。

ABADD,    ABADE,    ABADF
ABBDD,    ABBDE,    ABBDF
ABCDD,    ABCDE,    ABCDF

在搜索中,我还找到了 this,但我不完全确定如何围绕我的输入实现这一点。

将输入字符串分解为问号周围的多个子字符串是否最有效(因此上面的示例变为 AB + ? + D + ?)。像 list (s) 这样的东西适合这个吗?

在此先感谢您提供的任何帮助。

您可以使用 itertools.product to get the combinations and string.format to merge those into the template string. (First, replace the ? with {} to get format string syntax。)

def combine(template, options):
    template = template.replace('?', '{}')
    for opts in itertools.product(*options):
        yield template.format(*opts)

示例:

>>> list(combine('AB?D?', ['ABC', 'DEF']))
['ABADD', 'ABADE', 'ABADF', 'ABBDD', 'ABBDE', 'ABBDF', 'ABCDD', 'ABCDE', 'ABCDF']