python - 如何使用列表列表调用 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])))
,可以按需要工作——但我不想每次都指定元素。有时,列表有十几个元素。
谢谢!
解决方案
使用运算符解包列表*
:
list(itertools.product(*text_input))
# [('The', 'apple', 'is', 'green'),
# ('The', 'apple', 'is', 'red'),
# ('The', 'banana', 'is', 'green'),
# ('The', 'banana', 'is', 'red')]
推荐阅读
- python - 如何在aws s3中找到指定日期内的学生人数?
- docker - Jenkins+Docker:从 docker.inside() 提交更改
- c++ - 如何使用 SIMD 指令使预乘 alpha 函数更快?
- filter - 根据特定条件返回数组公式中的过滤器
- javascript - 用字母数字字符编号的 CSS 嵌套有序列表
- dictionary - 字典可以成为 Julia 结构的一部分吗?
- html - 如何阻止 div 相互堆叠?
- javascript - 将键值对中的数据发送到 api
- java - Java 流 - 在一次迭代中应用两个过滤器并收集到两个集合
- python - 如何确定数据类中的字段是否具有默认值或是否已显式设置?