I have a problem finding all combinations of a 2D array. Let’s suggest I have an array as follwoing:
JavaScript
x
6
1
[
2
[1,2],
3
[3,4],
4
[5,6]
5
]
6
Now I need to get all possible combninations such as
JavaScript
1
11
11
1
[
2
[1,3,5],
3
[1,3,6],
4
[1,4,5],
5
[1,4,6],
6
[2,3,5],
7
[2,3,6],
8
[2,4,5],
9
[2,4,6]
10
]
11
I’ve managed to get it with numpy and meshgrids with single arrays:
JavaScript
1
7
1
import numpy as np
2
array_1 = np.array([1,2])
3
array_2 = np.array([3,4])
4
array_3 = np.array([5,6])
5
6
combination = np.array(np.meshgrid(array_1, array_2, array_3)).T.reshape(-1,3)
7
But with a 2D array I cant’t get it to work.
JavaScript
1
4
1
import numpy as np
2
multi = [np.array([1,2]), np.array([3,4]), np.array([5,6])]
3
combination = np.array(np.meshgrid(multi)).T.reshape(-1,len(multi))
4
This doesn’t give me the expected result but only:
JavaScript
1
5
1
[
2
[1,2,3],
3
[4,5,6]
4
]
5
Is there any way to get this working correctly?
Advertisement
Answer
You can use the itertools
package in the standard library.
itertools.product
generates all combinations that you wish.
JavaScript
1
16
16
1
import itertools
2
arrays = [
3
[1,2],
4
[3,4],
5
[5,6]
6
]
7
list(itertools.product(*arrays))
8
#[(1, 3, 5),
9
# (1, 3, 6),
10
# (1, 4, 5),
11
# (1, 4, 6),
12
# (2, 3, 5),
13
# (2, 3, 6),
14
# (2, 4, 5),
15
# (2, 4, 6)]
16
If you prefer lists to tuples, you can do the following:
JavaScript
1
10
10
1
list(map(list, itertools.product(*arrays)))
2
#[[1, 3, 5],
3
# [1, 3, 6],
4
# [1, 4, 5],
5
# [1, 4, 6],
6
# [2, 3, 5],
7
# [2, 3, 6],
8
# [2, 4, 5],
9
# [2, 4, 6]]
10