0

In Python, I am looking for a generic way (i.e. itertools) to build an array with all possible combinations between a given one dimensional array and N one dimensional arrays.

Here is a simplified example.

Input

main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]

Expected output

[
  ["a1","b1","c1"],
  ["a1","b1","c2"],
  ["a1","b1","c3"],
  ["a1","b2","c1"],
  ["a1","b2","c2"],
  ["a1","b2","c3"],
  ["a2","b1","c1"],
  ["a2","b1","c2"],
  ["a2","b1","c3"],
  ....
  ["a3","b2","c3"]
]
TMichel
  • 4,336
  • 9
  • 44
  • 67

1 Answers1

3

You can do it with itertools.product() like so:

from itertools import product

main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]
[list(a) for a in product(main, *secondary)]

Output:

[['a1', 'b1', 'c1'],
 ['a1', 'b1', 'c2'],
 ['a1', 'b1', 'c3'],
 ['a1', 'b2', 'c1'],
 ['a1', 'b2', 'c2'],
 ['a1', 'b2', 'c3'],
 ['a2', 'b1', 'c1'],
 ['a2', 'b1', 'c2'],
 ['a2', 'b1', 'c3'],
 ['a2', 'b2', 'c1'],
 ['a2', 'b2', 'c2'],
 ['a2', 'b2', 'c3'],
 ['a3', 'b1', 'c1'],
 ['a3', 'b1', 'c2'],
 ['a3', 'b1', 'c3'],
 ['a3', 'b2', 'c1'],
 ['a3', 'b2', 'c2'],
 ['a3', 'b2', 'c3']]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78