查找所有可能的组合

3

我之前问过类似的问题,但是涉及到其他编程语言。

假设我有一些根、前缀和后缀。

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
...

1
所有列表的组合的重复。还有很多其他问题:http://stackoverflow.com/search?q=python+all+combinations。 - undefined
2个回答

10

使用itertools.product()函数:

for p, r, s in itertools.product(prefix, roots, suffix):
    print p, r, s

2

不需要导入库,因为Python已经内置了相关语法。与其只是打印输出,它会返回一个像您要求的数据结构,而且您还可以将字符串连接在一起:

combinations = [
    p + " " + t + " " + s
    for t in ts for p in prefix for s in suffix]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接