我正在使用 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/