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

时间:2015-01-10 21:21:57

标签: python combinatorics

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

假设我有一个列表列表:

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

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

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

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:1)

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

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