编辑数组中的所有其他项目 [英] Edit every other item in an array
本文介绍了编辑数组中的所有其他项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
matrix = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
vector = np.array([0,0,0,0])
对于矢量,您可以像这样编辑其他所有元素
For vectors, you can edit every other element like so
vector[1::2] = 1
这给出了
np.array([0,1,0,1])
但是;
matrix[1::2] = 1
收益
np.array([[0,0,0,0],[1,1,1,1],[0,0,0,0],[1,1,1,1]])
我想要输出
np.array([[0,1,0,1],[0,1,0,1],[0,1,0,1],[0,1,0,1]])
有一种蛮力方法来获取数组的形状,将其展平,使用[1 :: 2]并重塑形状,但是我敢肯定我缺少一个更优雅的解决方案.
There is a brute force approach to take the shape of the array, flatten it, use [1::2], and reshape, but i'm sure there is a more elegant solution i am missing.
任何帮助将不胜感激.
推荐答案
您可以对多维索引进行类似的操作
You can do something similar with multidimensional indexing
>>> matrix
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> matrix[:,1::2] = 1
>>> matrix
array([[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 0, 1]])
这篇关于编辑数组中的所有其他项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文