【发布时间】:2021-06-19 16:12:11
【问题描述】:
有没有更好的方法来做到这一点?就像用 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]]
【问题讨论】:
标签: python arrays numpy reshape