In [441]: parameter1 = [29.9, 30, 30.1]
...: parameter2 = [19.9, 20, 20.1]
itertools 有一个方便的product 函数:
In [442]: import itertools
In [443]: list(itertools.product(parameter1, parameter2))
Out[443]:
[(29.9, 19.9),
(29.9, 20),
(29.9, 20.1),
(30, 19.9),
(30, 20),
(30, 20.1),
(30.1, 19.9),
(30.1, 20),
(30.1, 20.1)]
这个列表可以放入你想要的数组形式:
In [444]: np.array(_).reshape(3,3,2)
Out[444]:
array([[[29.9, 19.9],
[29.9, 20. ],
[29.9, 20.1]],
[[30. , 19.9],
[30. , 20. ],
[30. , 20.1]],
[[30.1, 19.9],
[30.1, 20. ],
[30.1, 20.1]]])
添加另一个列表:
In [447]: C=list(itertools.product(parameter1, parameter2, parameter1))
In [448]: np.array(C).reshape(3,3,3,-1)
仅使用 numpy 函数:
np.stack(np.meshgrid(parameter1,parameter2,indexing='ij'), axis=2)
itertools.product 方法更快。
也受到重复答案的启发:
def foo(alist):
a,b = alist # 2 item for now
res = np.zeros((a.shape[0], b.shape[0],2))
res[:,:,0] = a[:,None]
res[:,:,1] = b
return res
foo([np.array(parameter1), np.array(parameter2)])
在此示例中,它的时间与itertools.product 大致相同。
In [502]: alist = [parameter1,parameter2,parameter1,parameter1]
In [503]: np.stack(np.meshgrid(*alist,indexing='ij'), axis=len(alist)).shape
Out[503]: (3, 3, 3, 3, 4)