1.生成n*m的零矩阵
def creat_array_0(n, m):
# 生成一个n*m的零矩阵
matrixA = [None] * n
for i in range(n):
matrixA[i] = [0] * m
matrixB = np.array(matrixA)
return matrixB
2.获取用户输入,然后通过遍历来更改内容
import numpy as np
def creat_array():
try:
n, m = map(int, input("请输入矩阵的行数与列数,中间用空格分隔:").split())
data = input('请一行一行地输入矩阵内容,元素之间用空格分隔:').split()
matrixA = [None] * n
for i in range(n):
matrixA[i] = [0] * m
for i in range(n):
for j in range(m):
num = data[i*m+j]
matrixA[i][j] = num
matrixB = np.array(matrixA)
return matrixB
except:
print("间隔请用空格")
3.生成n*m零矩阵也可以通过numpy的zeros函数来实现
import numpy as np
def creat_array_0(n, m):
# 生成一个n*m的零矩阵
matrixA = np.zeros((n,m))
return matrixA
4.所以第2段代码可以更改为
def creat_array():
try:
n, m = map(int, input("请输入矩阵的行数与列数,中间用空格分隔:").split())
data = input('请一行一行地输入矩阵内容,元素之间用空格分隔:').split()
matrixA = np.zeros((n,m))
for i in range(n):
for j in range(m):
num = data[i*m+j]
matrixA[i][j] = num
matrixB = np.array(matrixA)
return matrixB
except:
print("间隔请用空格")