所有可能的不同数组项的组合

时间:2016-10-15 02:26:10

标签: python arrays algorithm combinations

我有这样的数组:

[[1, 2], [3, 4]]
[[4, 5], [5, 6]]
[[7, 8], [8, 9]]

我想获得这些数组的所有可能组合:

[[1, 2], [4, 5], [7, 8]]
[[1, 2], [4, 5], [8, 9]]
[[1, 2], [5, 6], [7, 8]]
...

它可以是数组中的任意数量的数组。

我应该用什么方法来完成Python?

1 个答案:

答案 0 :(得分:4)

您需要笛卡儿产品

>>> 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]