Python 如何为n个列表的列表创建叉积元组?

Python 如何为n个列表的列表创建叉积元组?,python,python-3.x,pycharm,itertools,Python,Python 3.x,Pycharm,Itertools,例如,[[0,1],[0,1],[0,1]]我想得到000001…111的元组。当我循环遍历n个列表的列表时,它不适用于itertools.product product = [] for i in range(len(list)): product = itertools.product(product, list[i]) 从问题中可以明显看出,我是Python新手。提前谢谢。干杯 如果需要获取列表元素的cartesion乘积的元组,可以稍微更改代码 l = [[0,1],[0,1]

例如,[[0,1],[0,1],[0,1]]我想得到000001…111的元组。当我循环遍历n个列表的列表时,它不适用于itertools.product

product = []

for i in range(len(list)):
   product = itertools.product(product, list[i])

从问题中可以明显看出,我是Python新手。提前谢谢。干杯

如果需要获取列表元素的cartesion乘积的元组,可以稍微更改代码

l = [[0,1],[0,1],[0,1]]
>>> x = []
>>> for i in itertools.product(*l):
...     x.append(i)
... 
>>> x
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

itertools.product
非常适合您。文档非常清晰,但您可能需要看到它的实际应用:

>>> import itertools
>>> ls = [[0, 1], [0, 1], [0, 1]]
>>> list(itertools.product(*ls))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
如果您的
ls
将包含相同的iterables,那么您甚至不需要
ls
。将
repeat
关键字参数传递给
产品

>>> list(itertools.product([0, 1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

非常感谢,这就是我要找的。