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

2024-03-29 00:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,[[0,1],[0,1],[0,1]]我想得到000001…111的元组。当我在n个列表的列表中循环时,它不适用于itertools.产品你知道吗

product = []

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

从这个问题可以明显看出,我是Python的新手。提前谢谢。干杯。你知道吗


Tags: in列表forlen产品rangeproductlist
2条回答

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关键字参数传递给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)]

如果您需要获得列表元素的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)]

相关问题 更多 >