首页 > 解决方案 > 如何使用列表列表调用 itertools.pruduct 函数

问题描述

我正在尝试使用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]))),可以按需要工作——但我不想每次都指定元素。有时,列表有十几个元素。

谢谢!

标签: pythonlistitertools

解决方案


使用运算符解包列表*

list(itertools.product(*text_input))
# [('The', 'apple', 'is', 'green'), 
#  ('The', 'apple', 'is', 'red'), 
#  ('The', 'banana', 'is', 'green'), 
#  ('The', 'banana', 'is', 'red')]

推荐阅读