具有所有子列表变体的单个列表的 Pythonic 方式

Pythonic way of single list with all variations of sublists

我确定这个简单的问题有答案,但我真的不知道如何用英语表达它(惭愧),所以决定问问人类。

假设我有一个列表列表:

[['Sometimes'], [' '], ['I'], [' '], ['love', 'hate'], [' '], ['pizza', 'coke']]

获得以下输出的最 pythonic 方法是什么?

['Sometimes I love pizza', 'Sometimes I love coke', 'Sometimes I hate pizza', 'Sometimes I hate coke']

这可以用递归生成器很好地编写:

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)

然后

lists = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]
for s in sentences(lists):
    print s

打印

Sometimes I love pizza
Sometimes I love coke
Sometimes I hate pizza
Sometimes I hate coke

(要获得实际列表,list(sentences(lists))。)

from itertools import product

options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]

for combo in product(*options):
    print("".join(combo))

给予

Sometimes I love pizza
Sometimes I love coke
Sometimes I hate pizza
Sometimes I hate coke