python - 使用指定索引 reshape 数组

有没有更好的方法来做到这一点?喜欢用 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/

相关文章:

regex - 查找以 RegEx 结尾的字符串替换失败?谷歌脚本

rust - 关于位复制的 Copy 特性是否仅从堆栈复制?

haskell - 合并两个 Either Monad 的结果

javascript - Material-UI Select 在 onChange 后不更新

reactjs - 将 useState 与具有多个 bool 字段的对象 react

go - Helm : How to convert a string into lower/upp

regex - Perl - 如何从文本文件中省略行?

django - 如何从 drf-spectacular API 文档中删除 RetrieveUpd

c - 返回变量地址的函数如何返回零?

javascript - 不要将数字或单词替换为下划线,而是保留破折号并删除其周围的空格