python - 将可迭代列表传递给 itertools 函数

标签 python python-itertools

我正在使用 itertools.product 函数。我有一个 2 层嵌套列表,它是一个可迭代列表。我想将此传递给产品功能不知道如何正确格式化它。

说清楚,我要

In [37]: [k for k in product([1,2],['a','b'])]
Out[37]: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

但是从这样的 nested_list 输入生成

nested_list = [[1,2],['a','b']]

但是我得到了

In [36]: [k for k in product(nested_list)]
Out[36]: [([1, 2],), (['a', 'b'],)]

最佳答案

product 接受可变数量的参数,因此您需要解压缩列表。

list(product(*nested_list)) # without list() normally, of course

关于python - 将可迭代列表传递给 itertools 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780188/

相关文章:

python - 如何计算二维数组元素之间差异的所有组合?

python - 如何在 python 中切片进程 itertools.product?

python - itertools 是线程安全的吗?

python - 标签在 Odoo-9 中不显示

python - 用 numpy 拟合数据

python - 可逆笛卡尔积元素/索引转换功能

python - 查找字符串列表中的差异

Python装饰子类的所有方法,并提供重写的方法

python - Python无效语法为何?c

python - python 中的数字识别(OpenCV 和 pytesseract)