I have two arrays, for example:
array1 = [A, B, C]
array2 = [a, b, c]
I want to create a matrix which contain all the possible combinations between these two arrays in the following way with python code:
[[A, B, C]
[A, B, c]
[A, b, C]
[A, b, c]
[a, B, C]
[a, B, c]
[a, b, C]
[a, b, C]]
CodePudding user response:
Use itertools.product
and zip
:
array1 = ['A', 'B', 'C']
array2 = ['a', 'b', 'c']
from itertools import product
out = list(product(*zip(array1, array2)))
output:
[('A', 'B', 'C'),
('A', 'B', 'c'),
('A', 'b', 'C'),
('A', 'b', 'c'),
('a', 'B', 'C'),
('a', 'B', 'c'),
('a', 'b', 'C'),
('a', 'b', 'c')]
CodePudding user response:
from collections import deque
def foo(arr):
ans = deque([[]])
i = 0
while i < len(array1):
while len(ans[0]) == i:
curr = ans.popleft()
for el in arr:
ans.append(curr [el[i]])
i = 1
return ans
foo([array1, array2])
# deque([['A', 'B', 'C'],
# ['A', 'B', 'c'],
# ['A', 'b', 'C'],
# ['A', 'b', 'c'],
# ['a', 'B', 'C'],
# ['a', 'B', 'c'],
# ['a', 'b', 'C'],
# ['a', 'b', 'c']])
CodePudding user response:
array1=['A','B','C']
array2=['a','b','c']
array1.extend(array2)
allp = list()
for x in array1:
for y in array1:
for z in array1:
allp.append(x y z)
CodePudding user response:
You can recursively generate all possible combinations.
array1 = ['A','B','C']
array2 = ['a','b','c']
ans = []
def f(x, i):
if i == max(len(array1), len(array2)):
ans.append(x)
else:
try:
f(x [array1[i]], i 1)
except IndexError:
pass
try:
f(x [array2[i]], i 1)
except IndexError:
pass
f([], 0)
print(ans)
Note: This solution also works for arrays of different length. Like [A, B, C]
and [a, b, c, d]
.