Reputation: 12856
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.
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
...
Upvotes: 3
Views: 1681
Reputation: 8116
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]
Upvotes: 2
Reputation: 601341
Use itertools.product()
:
for p, r, s in itertools.product(prefix, roots, suffix):
print p, r, s
Upvotes: 10