0

Do you know how to compute the cartesian product of n lists and n dimensions arrays?

example:

d = 3
x = [0, 1, 2]
y = [0, 1, 2]

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
eliorn23
  • 9
  • 2
  • 1
    You example is ambiguous, what would be the result for `x = [1, 2, 3] ; y = [10, 20, 30]`? – mozway Jan 27 '22 at 16:17

1 Answers1

1

Please check if the below-mentioned solution works for you, do let me know if any changes are required:

import itertools

d = 3
x = [0, 1, 2]
y = [0, 1, 2]
third_lst = [0, 1, 2] # this list is required for the third dimension

input_lst = [x, y, third_lst]

final_lst = list(itertools.product(*input_lst))

print(final_lst)

Output:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
Piyush Sambhi
  • 843
  • 4
  • 13