【发布时间】:2014-12-04 04:53:51
【问题描述】:
我有一个如下所示的n维数组:
np.array([[0,3],[0,3],[0,10]])
在此数组中,元素表示低值和高值。例如:[0,3] 指的是[0,1,2,3]
我需要使用上面给出的范围生成所有值的组合。
比如我要[0,0,0], [0,0,1] ... [0,1,0] ... [3,3,10]
我已经尝试了以下方法来得到我想要的:
ds = np.array([[0,3],[0,3],[0,10]])
nItems = int(reduce(lambda a,b: a * (b[1] - b[0] + 1), ds, 1))
myCombinations = np.zeros((nItems,))
nArrays = []
for x in range(ds.shape[0]):
low = ds[x][0]
high= ds[x][1]
nitm = high - low + 1
ar = [x+low for x in range(nitm) ]
nArrays.append(ar)
myCombinations = cartesian(nArrays)
笛卡尔函数取自Using numpy to build an array of all combinations of two arrays
我需要这样做几百万次。
我的问题:有没有更好/更有效的方法来做到这一点?
【问题讨论】:
标签: python arrays numpy combinations