I'm sure there are answers to this simple question but I don't really know how to formulate it in English (ashamed), so decided to ask human beings.
Suppose I have a list of lists:
[['Sometimes'], [' '], ['I'], [' '], ['love', 'hate'], [' '], ['pizza', 'coke']]
What would be the most pythonic way to obtain the following output?
['Sometimes I love pizza', 'Sometimes I love coke', 'Sometimes I hate pizza', 'Sometimes I hate coke']
from itertools import product
options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]
for combo in product(*options):
print("".join(combo))
gives
Sometimes I love pizza
Sometimes I love coke
Sometimes I hate pizza
Sometimes I hate coke
This can be written nicely with a recursive generator:
def sentences(lists, i=0, sentence=''):
if i == len(lists):
yield sentence
else:
for word in lists[i]:
yield from sentences(lists, i + 1, sentence + word)
And then
lists = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]
for s in sentences(lists):
print s
which prints
Sometimes I love pizza
Sometimes I love coke
Sometimes I hate pizza
Sometimes I hate coke
(To get an actual list, list(sentences(lists))
.)
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