Reputation: 11
I have a 2-dimensional array like [[1,2,3], [4,5,6], [7,8,9]].
So I need to combine every element with all the others form another sublists ang get an array like [[1,4,7], [1,4,8], [1,4,9], [2,4,7], [2,4,8], [2,4,9], [3,4,7], [3,4,8], [3,4,9], [1,5,7], [...], [...], ... etc] in Python3.
! The number of sublists may be different.
I have used different approaches with loops but nothing works correctly. How can I do that without using itertools? Thanks in advance!
I tried iterating arrays but I could not fully embody the idea.
arr = [[1,2,3], [4,5,6], [7,8,9]]
total = []
for i in arr[0]:
for index, j in enumerate(arr[1:]):
res = [i]
for indx, n in enumerate(j):
res.append(n)
for m in arr[index+1]:
res.append(m)
break
print(res)
And I got only this
[1, 4, 4, 5, 4, 6, 4]
[1, 7, 7, 8, 7, 9, 7]
[2, 4, 4, 5, 4, 6, 4]
[2, 7, 7, 8, 7, 9, 7]
[3, 4, 4, 5, 4, 6, 4]
[3, 7, 7, 8, 7, 9, 7] .. which is not correct.
Upvotes: 1
Views: 27
Reputation: 389
Just use the cartesian product from itertools
from itertools import product
arr = [[1,2,3], [4,5,6], [7,8,9]]
prod = product(*arr)
print(list(prod))
Upvotes: 1