【python学习笔记】Numpy 例题

时间:2024-11-20 07:41:31

创造一个边界值为1而内部都是0的数组

#第一种方法
import numpy as np
a = np.zeros((10,10),dtype=float)
for i in range(0,10):
    for j in range(0,10):
        if i == 0 or i == 9 or j == 0 or j == 9:
            a[i][j] = 1
print(a)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

[[ 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
S = np.ones((10, 10))
S[1:9, 1:9] = 0
print(S)
  • 1
  • 2
  • 3
  • 4
  • 5

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