有没有更好的方法来做到这一点?喜欢用 numpy 函数替换列表理解吗?我假设对于少量元素,差异微不足道,但对于更大的数据 block ,这会花费太多时间。
>>> 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
https://stackoverflow.com/questions/66755828/