我正在尝试使用itertools.product函数从替代单词列表中创建句子的所有组合。输入是一个列表列表,每个元素是一个备用单词列表。例如:
text_input = [['The'],
['apple', 'banana'],
['is'],
['green', 'red']]
以及每个列表中一个单词的所有排列的所需输出列表:
[['The apple is red'],
['The banana is red'],
['The apple is green'],
['The banana is green']]
但是当我尝试做类似的事情时:
print(list(itertools.product(text_input)))
>>> [(['The'],), (['apple', 'banana'],), (['is'],), (['green', 'red'],)]
与此相反,它print(list(itertools.product(text_input[0], text_input[1],text_input[2],text_input[3])))
可以按需工作-但我不想每次都指定元素。有时,列表包含许多元素。
谢谢!
使用*
运算符解压缩列表:
list(itertools.product(*text_input))
# [('The', 'apple', 'is', 'green'),
# ('The', 'apple', 'is', 'red'),
# ('The', 'banana', 'is', 'green'),
# ('The', 'banana', 'is', 'red')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句