首页 > 解决方案 > 将矩阵与标量相乘

问题描述

我需要创建一个函数,将矩阵与标量相乘而不使用 numpy。这里的问题是该函数不返回矩阵。(因此对于下面的矩阵,它需要返回 [[2,4],[6,9.0],[10,84]]

def mul_mat_by_scalar(mat, alpha):

           # Write the rest of the code for question 5 below here.

    mat_new = []

    for j in mat:

        for i in j:

            a = (i* alpha)

            mat_new.append(a)

            continue

    return mat_new  

print mul_mat_by_scalar([[1,2], [3,4.5], [5,42]], 2)

标签: python

解决方案


我宁愿使用这样的列表理解:

def mul_mat_by_scalar(mat, alpha):
    return [[alpha*j for j in i] for i in mat]

它只是将每个元素乘以matalpha返回新矩阵。

对于您的工作方法,您必须附加列表而不仅仅是a. 你会写这样的东西:

def mul_mat_by_scalar(mat, alpha):

           # Write the rest of the code for question 5 below here.

    mat_new = []
    for j in mat:     
        sub_mat=[]
        for i in j:
            a = i* alpha
            sub_mat.append(a)
        mat_new.append(sub_mat)

    return mat_new

但那是丑陋的,而不是蟒蛇


推荐阅读