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]
精彩评论