问题描述
有没有更好的方法来做到这一点?喜欢用 numpy 函数替换列表理解?我假设对于少量元素,差异微不足道,但对于较大的数据块,则需要太多时间。
>>> rows = 3
>>> cols = 3
>>> target = [0,4,7,8] # each value represent target index of 2-d array converted to 1-d
>>> x = [1 if i in target else 0 for i in range(rows * cols)]
>>> arr = np.reshape(x,(rows,cols))
>>> arr
[[1 0 0]
[0 1 0]
[0 1 1]]
解决方法
另一种方式:
shape = (rows,cols)
arr = np.zeros(shape)
arr[np.unravel_index(target,shape)] = 1
,
由于 x
来自一个范围,您可以索引一个零数组来设置这些:
x = np.zeros(rows * cols,dtype=bool)
x[target] = True
x = x.reshape(rows,cols)
或者,您可以预先创建适当的形状并分配给散乱的数组:
x = np.zeros((rows,cols),dtype=bool)
x.ravel()[target] = True
如果您想要实际的零和一,请使用 np.uint8
之类的 dtype 或除 bool
之外的任何其他适合您需求的类型。
此处显示的方法甚至适用于您的列表示例,以提高效率。即使您将 target
转换为 set
,您也正在使用 O(N)
执行 N = rows * cols
查找。相反,您只需要 M
赋值,无需查找,使用 M = len(target)
:
x = [0] * (rows * cols)
for i in target:
x[i] = 1