我正在尝试创建矩阵函数:def create_matrix(* NumList,行,列)。
def create_matrix(*NumList, rows, cols):
Fmat = []
if len(NumList) == rows*cols:
for i in range(rows):
Imat = []
for j in range(cols):
Imat.append(NumList[rows * i + j])
Fmat.append(Imat)
return Fmat
else:
print("The number of elememnts does not match the shape of the matrix.")
对于create_matrix(* range(4,19),行= 3,列= 5),所需的输出应为:
[[4, 5, 6, 7, 8], [9, 10, 11, 12, 13], [14, 15, 16, 17, 18]]
。
但是,我只能产生以下结果。任何解决方案,谢谢!
[[4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]
您可以使用函数来传递行数或列数,甚至可以在函数本身中进行修改。甚至可以使用input()函数询问行数。
def workingWithMatrix(m ,n):
#m: number of rows
# n: number of columns
mat = []
for i in range(0,n):
mat.append([])
for i in range(0,m):
for j in range(0,n):
mat[i].append(j)
mat[i][j] = 0
for i in range(0,m):
for j in range(0,n):
print('Value in row: ', i+1, 'column: ', j+1)
mat[i][j] = int(input())
print(mat)
此功能允许用户介绍矩阵中每个项目的值。
只需稍作改动,即可正常工作。将rows * i + j
代替cols * i + j
:
Imat.append(NumList[cols * i + j])
只需对您的代码进行少量更改:
def create_matrix(*NumList, rows, cols):
Fmat = []
if len(NumList) == rows*cols:
for i in range(rows):
Imat = []
for j in range(cols):
Imat.append(NumList[cols * i + j])
Fmat.append(Imat)
return Fmat
else:
print("The number of elememnts does not match the shape of the matrix")
n_l= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(create_matrix(*n_l, rows= 3, cols=5))
print(create_matrix(*n_l, rows= 5, cols=3))
输出:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]