如何为 n 个列表的列表创建叉积元组?
How can I create crossproduct tuple for list of n list?
例如 [[0,1],[0,1],[0,1]] 我想得到 000,001 的元组...111.When 我遍历 n 个列表的列表,它不适用于 itertools.product
product = []
for i in range(len(list)):
product = itertools.product(product, list[i])
从问题中可以看出,我是Python的新手。提前致谢。干杯。
如果您需要获取列表元素的笛卡尔积的元组,您可以稍微更改您的代码。
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
将包含相同的可迭代对象,那么您甚至不需要 ls
。改为将 repeat
关键字参数传递给 product
:
>>> 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)]
例如 [[0,1],[0,1],[0,1]] 我想得到 000,001 的元组...111.When 我遍历 n 个列表的列表,它不适用于 itertools.product
product = []
for i in range(len(list)):
product = itertools.product(product, list[i])
从问题中可以看出,我是Python的新手。提前致谢。干杯。
如果您需要获取列表元素的笛卡尔积的元组,您可以稍微更改您的代码。
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
将包含相同的可迭代对象,那么您甚至不需要 ls
。改为将 repeat
关键字参数传递给 product
:
>>> 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)]