如何使用列表列表调用 itertools.pruduct 函数
How to call itertools.pruduct function with list of lists
我正在尝试使用 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])))
可以正常工作——但我不想每次都指定元素。有时,列表中有十几个元素。
谢谢!
Unpack 使用 *
运算符的列表:
list(itertools.product(*text_input))
# [('The', 'apple', 'is', 'green'),
# ('The', 'apple', 'is', 'red'),
# ('The', 'banana', 'is', 'green'),
# ('The', 'banana', 'is', 'red')]
我正在尝试使用 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])))
可以正常工作——但我不想每次都指定元素。有时,列表中有十几个元素。
谢谢!
Unpack 使用 *
运算符的列表:
list(itertools.product(*text_input))
# [('The', 'apple', 'is', 'green'),
# ('The', 'apple', 'is', 'red'),
# ('The', 'banana', 'is', 'green'),
# ('The', 'banana', 'is', 'red')]