0

我正在尝试创建一个矩阵函数:def create_matrix(*NumList, rows, cols)。

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), rows=3, cols=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]]

4

5 回答 5

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)

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

于 2020-04-20T10:19:02.087 回答
0

只是一个小的改变,它工作正常。而不是rows * i + jput cols * i + j

Imat.append(NumList[cols * i + j])
于 2020-04-20T10:19:11.777 回答
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]]
于 2020-04-20T10:20:05.193 回答
0

使用列表理解

def create_matrix(*NumList, rows, cols):
    matrix = []
    if len(NumList) == rows * cols:
        for x in range(rows):
            matrix.append(list(NumList[x * cols:(x+1)*cols]))
        return matrix
    else:
        print("The number of elememnts does not match the shape of the matrix.")


if __name__ == "__main__":
    print(create_matrix(*range(4, 19), rows=3, cols=5))
于 2020-04-20T10:38:05.907 回答
0

您可以使用列表推导并这样编写:

def create_matrix(*values,rows,cols):
    return [  [*values[r:r+cols]] for r in range(0,rows*cols,cols) ]

这种方法的推广将允许您创建任意维数的矩阵:

def matrix(dims,*values):
    if len(dims) == 1: return list(values)
    block = 1
    for d in dims[1:]: block *= d
    return [ matrix(dims[1:],*values[r:r+block]) for r in range(0,dims[0]*block,block)]

m = matrix((3,2,3),*range(4, 22))
print(m)
# [[[4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15]], [[16, 17, 18], [19, 20, 21]]]
于 2020-04-20T14:31:30.453 回答