找到所有可能的组合
我之前问过这个问题,不过是关于其他编程语言的。
假设我有一些词根、前缀和后缀。
roots = ["car insurance", "auto insurance"]
prefix = ["cheap", "budget"]
suffix = ["quote", "quotes"]
在Python中有没有简单的函数,可以让我把这三个字符向量的所有可能组合都生成出来。
我想要一个列表或者其他数据结构,能返回每个字符串的所有可能组合的列表。
cheap car insurance quotes
cheap car insurance quotes
budget auto insurance quotes
budget insurance quotes
...
2 个回答
2
其实你不需要导入任何库,因为Python本身就有这个功能。它不仅仅是打印出来,而是返回你想要的数据结构,而且你还可以把字符串连接在一起:
combinations = [
p + " " + t + " " + s
for t in ts for p in prefix for s in suffix]
10
for p, r, s in itertools.product(prefix, roots, suffix):
print p, r, s