我有兩個陣列,例如:
array1 = [A, B, C]
array2 = [a, b, c]
我想創建一個矩陣,其中包含這兩個陣列之間的所有可能組合,使用 python 代碼的方式如下:
[[A, B, C]
[A, B, c]
[A, b, C]
[A, b, c]
[a, B, C]
[a, B, c]
[a, b, C]
[a, b, C]]
uj5u.com熱心網友回復:
使用itertools.product和zip:
array1 = ['A', 'B', 'C']
array2 = ['a', 'b', 'c']
from itertools import product
out = list(product(*zip(array1, array2)))
輸出:
[('A', 'B', 'C'),
('A', 'B', 'c'),
('A', 'b', 'C'),
('A', 'b', 'c'),
('a', 'B', 'C'),
('a', 'B', 'c'),
('a', 'b', 'C'),
('a', 'b', 'c')]
uj5u.com熱心網友回復:
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']])
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
您可以遞回生成所有可能的組合。
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)
注意:此解決方案也適用于不同長度的陣列。喜歡[A, B, C]和[a, b, c, d]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370117.html
