您需要笛卡尔积 。
>>> arrays = [
... [[1, 2], [3, 4]],
... [[4, 5], [5, 6]],
... [[7, 8], [8, 9]],
... ]
>>> import itertools
>>> from pprint import pprint
>>> pprint(list(itertools.product(*arrays)))
[([1, 2], [4, 5], [7, 8]),
([1, 2], [4, 5], [8, 9]),
([1, 2], [5, 6], [7, 8]),
([1, 2], [5, 6], [8, 9]),
([3, 4], [4, 5], [7, 8]),
([3, 4], [4, 5], [8, 9]),
([3, 4], [5, 6], [7, 8]),
([3, 4], [5, 6], [8, 9])]
由于列表的存储方式有点模棱两可:
>>> x,y,z = arrays
>>> x
[[1, 2], [3, 4]]
>>> y
[[4, 5], [5, 6]]
>>> z
[[7, 8], [8, 9]]
>>> pprint(list(itertools.product(x,y,z)))
[([1, 2], [4, 5], [7, 8]),
([1, 2], [4, 5], [8, 9]),
([1, 2], [5, 6], [7, 8]),
([1, 2], [5, 6], [8, 9]),
([3, 4], [4, 5], [7, 8]),
([3, 4], [4, 5], [8, 9]),
([3, 4], [5, 6], [7, 8]),
([3, 4], [5, 6], [8, 9])]
>>>
当然, itertools.product等效于嵌套的for循环:
>>> for s1 in x:
... for s2 in y:
... for s3 in z:
... print(s1,s2,s3)
...
[1, 2] [4, 5] [7, 8]
[1, 2] [4, 5] [8, 9]
[1, 2] [5, 6] [7, 8]
[1, 2] [5, 6] [8, 9]
[3, 4] [4, 5] [7, 8]
[3, 4] [4, 5] [8, 9]
[3, 4] [5, 6] [7, 8]
[3, 4] [5, 6] [8, 9]
>>>
注意:
>>> for s in itertools.product(*arrays):
... print(*s)
...
[1, 2] [4, 5] [7, 8]
[1, 2] [4, 5] [8, 9]
[1, 2] [5, 6] [7, 8]
[1, 2] [5, 6] [8, 9]
[3, 4] [4, 5] [7, 8]
[3, 4] [4, 5] [8, 9]
[3, 4] [5, 6] [7, 8]
[3, 4] [5, 6] [8, 9]