如何使用Python创建矩阵而不使用numpy

问题描述 投票:0回答:2

我正在尝试创建矩阵函数: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]]

python
2个回答
0
投票

您可以使用函数来传递行数或列数,甚至可以在函数本身中进行修改。甚至可以使用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)

此功能允许用户介绍矩阵中每个项目的值。


0
投票

只需稍作改动,即可正常工作。将rows * i + j代替cols * i + j

Imat.append(NumList[cols * i + j])

0
投票

只需对您的代码进行少量更改:

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]]
© www.soinside.com 2019 - 2024. All rights reserved.