Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of single list with all variations of sublists

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']
like image 219
c0rdis Avatar asked Jan 10 '15 21:01

c0rdis


2 Answers

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
like image 99
Hugh Bothwell Avatar answered Oct 05 '22 03:10

Hugh Bothwell


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)).)

like image 29
Paul Draper Avatar answered Oct 05 '22 04:10

Paul Draper