在Python中,我正在寻找一种通用的方法(即itertools)来构建一个array
,其中包含给定的一维数组和N个一维数组之间的所有可能组合。
这是一个简化的例子。
main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]
[
["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"]
]
答案 0 :(得分:3)
您可以使用itertools.product()
执行此操作:
from itertools import product
main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]
[list(a) for a in product(main, *secondary)]
输出:
[['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']]