I'm trying to figure out how, given multiple values, I can generate all combinations of the values when applies to a template / pattern. So if I have the following variables:
pattern = '{name} likes {animal}s'
options = {'name': ['Alex', 'Sarah', 'Bob'], 'animal': ['cat', 'dog']}
I'd like to have the code print out all the possible combinations based on the string pattern and the values in the dictionary (or any other structure, it doesn't matter)
'Alex likes cats'
'Alex likes dogs'
'Sarah likes cats'
'Sarah likes dogs'
'Bob likes cats'
'Bob likes dogs'
I can think of some ways do it, but it's messy, and I'm trying to find a way to do this without hardcoding, so in the future I could introduce a new key, like 'color' without having to change anything but pattern and options
I'm assuming I can use something similar to this code I found:
def combine(template, options):
for opts in itertools.product(*options):
yield template.format(*opts)
But I can't figure out how to get all the combinations and keep them in a format that string.format() will accept. I'm sure there's some simple solution I'm overlooking.
So I found this out after stumbling upon another question, I'll leave it up in case this helps anyone else:
def combine(template, options)
products = [dict(zip(options, values)) for values in itertools.product(*options.values())]
return [template.format(**p) for p in products]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With