使用numpy打印nxn棋盘模式
给定n,打印n x n矩阵的棋盘图案
n=8的棋盘图案:
它由n*n个白色和黑色交替出现的方块组成,0代表白色,1代表黑色。
我们可以使用嵌套的for循环和一些if条件来做同样的事情,但是使用Python的numpy库,我们可以导入一个二维矩阵,并使用切片法得到棋盘图案。
我们将使用以下Python函数来打印图案:
**x = np.zeros((n, n), dtype=int)**
使用这个函数,我们使用numpy初始化一个所有下标都为0的二维矩阵
- x[1::2,::2] = 1:从第1索引行开始切片,直到1+2+2…,然后从第0到0+2+2…填充所有columns,以此类推。
 - x[::2, 1::2] = 1:从第0行开始切片,直到0+2+2…,并将所有columns填满1,从1到1+2+2+…
 
函数np.zeros((n, n), dtype=int):通常,数组的元素最初是未知的,但其大小是已知的。因此,NumPy提供了几个函数来创建具有初始占位符内容的arrays。这样就尽量减少了增长arrays的必要性,这是一种昂贵的操作。使用dtype形参初始化所有数据类型为int的值。
例如:np.zeros, np.ones等。
# Python program to print nXn
# checkerboard pattern using numpy
  
import numpy as np
  
# function to print Checkerboard pattern
def printcheckboard(n):
      
    print("Checkerboard pattern:")
  
    # create a n * n matrix
    x = np.zeros((n, n), dtype = int)
  
    # fill with 1 the alternate rows and columns
    x[1::2, ::2] = 1
    x[::2, 1::2] = 1
      
    # print the pattern
    for i in range(n):
        for j in range(n):
            print(x[i][j], end =" ") 
        print() 
  
  
# driver code
n = 8
printcheckboard(n)
输出:
Checkerboard pattern:
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 
基于跳棋盘总是偶数nXn的假设的改进源代码,即n是偶数。
# Python program to print nXn Assuming that n 
# is always even as a checkerboard was
  
import numpy as np
def printcheckboard(n):
    final = []
    for i in range(n):
        final.append(list(np.tile([0,1],int(n/2))) if i%2==0 else list(np.tile([1,0],int(n/2))))
    print(np.array(final))
  
  
# driver code
n = 8
printcheckboard(n)
输出:
Checkerboard pattern:
[[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]]
极客教程