开发者

Find all possible combinations

开发者 https://www.devze.com 2023-03-12 16:45 出处:网络
I asked this question earlier but regarding another programming languages. Let\'s say I have a couple roots, prefixes, and suffixes.

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 f开发者_如何学Cunction in Python which will allow me to construct all possible combinations of the three character vectors.

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():

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

精彩评论

暂无评论...
验证码 换一张
取 消