从python中的输入生成组合 [英] Generate combinations from an input in python
问题描述
我不确定如何在Python中进行此操作。在搜索时,我遇到过itertools,但是我不确定在这种情况下如何应用它。
I'm not sure how to go about this in Python. In searching for this, I have come across itertools but I'm not sure how I might apply it in this case.
我要做的是创建一个脚本可以接受包含查询标记(例如AB?D?)和一组选项(ABC,DEF)的字符串输入,以输出所有可能的组合,如下所示。
What I am trying to do is create a script that can take a string input containing query marks (like AB?D?) and a set of options (ABC, DEF) to output all of the possible combinations, like below.
ABADD, ABADE, ABADF
ABBDD, ABBDE, ABBDF
ABCDD, ABCDE, ABCDF
在搜索中,我还发现了此但是我不确定我如何才能在输入周围实现这一点。
In searching, I also found this but I'm not entirely sure how I might be able to implement this around my input.
将输入字符串分解成多个围绕问号的子字符串是最有效的(因此上面的示例变为AB +?+ D +?)。像清单这样的东西适合吗?
Would it be most efficient to break down the input string into multiple substrings around the question marks (so the above example becomes AB + ? + D + ?). Would something like list (s) be suitable for this?
在此先感谢您提供的任何帮助。
Thanks in advance for any help offered.
推荐答案
您可以使用 itertools.product
以获得组合和 string.format
会将其合并到模板字符串中。 (首先,将?
替换为 {}
以获得格式字符串语法。)
You can use 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']
这篇关于从python中的输入生成组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!