1.建立一個邊界值爲1而內部都是0的數組,圖例以下:
[提示:]解此題能夠先把全部值都設置爲1,這是大正方形;其次,把邊界除外小正方形所有設置爲0。
本題用到numpy的切片原理。多維數組一樣遵循x[start:stop:step]的原理。
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]數組
import numpy as np a = np.ones((10,10),int) a[1:9,1:9] = 0 print(a)
2.在數組主對角線上建立一個值爲1,2,3,4的5x5矩陣,圖例以下:
[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]dom
import numpy as np a = np.zeros((4,4),int) for i in range(4): for j in range(4): if(i==j): a[i][j]=j+1 print(a)
3.數組歸一化操做
生成一個隨機的5*5矩陣,找出最大值和最小值,而後把最大值和最小值分別用1和0表示,其餘值則介於在0和1中間。spa
import numpy as np a = np.random.rand(5,5) a[a == a.max()] = 1 a[a == a.min()] = 0 print(a)