Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy矩阵检查板图案更改_Python_Numpy - Fatal编程技术网

Python numpy矩阵检查板图案更改

Python numpy矩阵检查板图案更改,python,numpy,Python,Numpy,嗨,我正在尝试创建带有棋盘格模式的矩阵,其中,第一个[0,0]索引值是1。目前,我能够创建此矩阵: Z = np.zeros((8,8),dtype=int) Z[1::2,::2] = 1 Z[::2, 1::2] = 1 print(Z) [[0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1

嗨,我正在尝试创建带有棋盘格模式的矩阵,其中,第一个[0,0]索引值是1。目前,我能够创建此矩阵:

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2, 1::2] = 1
print(Z)

[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
但我希望是这样:

[[1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]]

通过我的努力和成功,我做到了:

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2, 1::2] = 1
Z[Z==0]=2
Z[Z==1]=0
Z[Z==2]=1
print(Z)




 [[1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]]

换句话说,也许有更有效的方法可以做到这一点?

正如您所建议的,一种方法是分配1并在矩阵中设置0:

Z = np.ones((8, 8), dtype=np.int)
Z[1::2, ::2] = Z[::2, 1::2] = 0
另一种方法,正如@divakar所建议的那样,是将你的指数固定下来:

Z = np.zeros((8, 8), dtype=np.int)
Z[1::2, 1::2] = Z[::2, ::2] = 1

可能:
Z[::2,::2]=1;Z[1::2,1::2]=1
?这是正确的,因为使用临时值交换数组中的所有值,因此效率低下。我已经向您展示了一种更简单的方法,它不需要在我的答案中进行交换。@AlexT请选择这个答案,如果它回答了您满意的问题。