0

I have arrays like this:

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

I want to get all possible combinations of these arrays:

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

It can be any number of arrays inside an array.

What approach should I use to accomplish it with Python?

Tom
  • 787
  • 1
  • 12
  • 28

1 Answers1

4

You want the Cartesian product.

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

Since it is a bit ambiguous how your lists are stored:

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

Of course, itertools.product is the equivalent of nested for-loops:

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

Notice:

>>> 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]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172