简体   繁体   English

找出所有可能的组合

[英]Find all possible combinations

I asked this question earlier but regarding another programming languages.我之前问过这个问题,但是关于另一种编程语言。

Let's say I have a couple roots, prefixes, and suffixes.假设我有几个词根、前缀和后缀。

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

Is there a simple function in Python which will allow me to construct all possible combinations of the three character vectors. Python 中是否有一个简单的 function 可以让我构造三个字符向量的所有可能组合。

So I want a list or other data structures which returns the following list of all possible combinations of each string.所以我想要一个列表或其他数据结构,它返回每个字符串的所有可能组合的以下列表。

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

Use itertools.product() :使用itertools.product()

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

There's no need to import libraries as Python has builtin syntax for this already.无需导入库,因为 Python 已经为此提供了内置语法。 Rather than just printing, it returns a data structure like you asked for, and you get to join the strings together to boot:它不仅会打印,还会返回您要求的数据结构,并且您可以将字符串连接在一起以进行引导:

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