扩展Python中的组合集

扩展Python中的组合集

我甚至不知道如何用语言来解释我要做的事情,所以我要举几个例子:
我想在一个字符串中设置一组选项,如下所示(如果这样更简单,格式可以更改):

is (my|the) car (locked|unlocked) (now)?

并让它吐出以下字符串列表:
is my car locked
is the car locked
is my car unlocked
is the car unlocked
is my car locked now
is the car locked now
is my car unlocked now
is the car unlocked now

我需要能够为Alexa应用程序这样做,因为它不接受自然语言处理的regex(为什么!?).
提前谢谢。

最佳答案

你可能想要的是itertools.product()。例如,您可以这样使用它:

import itertools

# set up options
opt1 = ["my", "the"]
opt2 = ["locked", "unlocked"]
opt3 = [" now", ""] # You'll have to use an empty string to make something optional

# The sentence you want to template
s = "is {} car {}{}?"

# Do all combinations
for combination in itertools.product(opt1, opt2, opt3):
    print(s.format(*combination))

这张照片:
is my car locked now?
is my car locked?
is my car unlocked now?
is my car unlocked?
is the car locked now?
is the car locked?
is the car unlocked now?
is the car unlocked?

关于python - 扩展Python中的组合集?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40979747/

10-09 17:18