2024-03-29 00:33:08 发布
网友
例如,[[0,1],[0,1],[0,1]]我想得到000001…111的元组。当我在n个列表的列表中循环时,它不适用于itertools.产品你知道吗
product = [] for i in range(len(list)): product = itertools.product(product, list[i])
从这个问题可以明显看出,我是Python的新手。提前谢谢。干杯。你知道吗
itertools.product适合你。文档非常清晰,但您可能需要看到它的实际应用:
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:
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)]
itertools.product
适合你。文档非常清晰,但您可能需要看到它的实际应用:如果您的
ls
将包含相同的iterables,那么您甚至不需要有ls
。将repeat
关键字参数传递给product
:如果您需要获得列表元素的cartesion乘积的元组,您可以对代码进行一些更改。你知道吗
相关问题 更多 >
编程相关推荐