假设我有以下列表,如何实现:
列表1 列表2 列表3
1 1 1
2 2 2
3 3 3
。 。 .
。 。 .
我想要迭代的行为如下:
1,1,1
1,1,2
1,1,3
1,2,1
1,2,2
1,2,3
1,3,1
1,3,2
1,3,3
2,1,1
.
.
.
这是三个列表会发生什么的演示,但在我的实际用例中,我事先不知道列表的数量。
最佳答案
how about when we don't know the number of lists in advance?
在这种情况下,您可以使用 itertools.product
,假设您有一个容器 lists
来保存任意数量的列表。
演示:
>>> from itertools import product
>>>
>>> lists = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for value in product(*lists):
... print(value)
...
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)
(1, 3, 1)
(1, 3, 2)
(1, 3, 3)
(2, 1, 1)
(2, 1, 2)
(2, 1, 3)
(2, 2, 1)
(2, 2, 2)
(2, 2, 3)
(2, 3, 1)
(2, 3, 2)
(2, 3, 3)
(3, 1, 1)
(3, 1, 2)
(3, 1, 3)
(3, 2, 1)
(3, 2, 2)
(3, 2, 3)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)
关于python - 如何像使用嵌套 for 循环一样迭代任意数量的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572169/