我确信这个简单的问题有答案,但我真的不知道如何用英语表达(惭愧),所以决定问人类。
假设我有一个列表列表:
[['Sometimes'], [' '], ['I'], [' '], ['love', 'hate'], [' '], ['pizza', 'coke']]
获得以下输出的最pythonic方法是什么?
['Sometimes I love pizza', 'Sometimes I love coke', 'Sometimes I hate pizza', 'Sometimes I hate coke']
答案 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))
。)