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 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.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

关于python - numpy 矩阵棋盘图案变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43630941/

相关文章:

python - 溢出错误 : math range error

python - 使用 Numpy 将 Python 库静态链接到 C (C++)

python - 无法填充 NumPy datetime64 数组

arrays - Python 增加数组的一部分

python - 使用 Scipy.opt 进行 Andrew NG Logistic 回归中的形状误差

python - 如何将给定行 `i` 或列 `j` 与标量相乘?

python - opencv haar文件返回太多面部特征

掷骰子模拟器的Python数据结构

python - Pandas 在不手动指定级别的情况下在多索引列上融化 (Python 3.5.1)

python - 从分割的路径字符串构建新的路径字符串