繁体   English   中英

找出所有可能的组合

[英]Find all possible combinations

我之前问过这个问题,但是关于另一种编程语言。

假设我有几个词根、前缀和后缀。

roots = ["car insurance", "auto insurance"]
prefix = ["cheap", "budget"]
suffix = ["quote", "quotes"]

Python 中是否有一个简单的 function 可以让我构造三个字符向量的所有可能组合。

所以我想要一个列表或其他数据结构,它返回每个字符串的所有可能组合的以下列表。

cheap car insurance quotes
cheap car insurance quotes
budget auto insurance quotes
budget insurance quotes
...

使用itertools.product()

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

无需导入库,因为 Python 已经为此提供了内置语法。 它不仅会打印,还会返回您要求的数据结构,并且您可以将字符串连接在一起以进行引导:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM