python - 将矩阵与标量相乘
问题描述
我需要创建一个函数,将矩阵与标量相乘而不使用 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)
解决方案
我宁愿使用这样的列表理解:
def mul_mat_by_scalar(mat, alpha):
return [[alpha*j for j in i] for i in mat]
它只是将每个元素乘以mat
并alpha
返回新矩阵。
对于您的工作方法,您必须附加列表而不仅仅是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
但那是丑陋的,而不是蟒蛇
推荐阅读
- python - 如何在python中四舍五入?例如,45.722 到 45.72、45.0 到 45.00
- android - 在 Nrwl NX monorepo 中使用 angular ionic
- c++ - C++ msvc compiler not type checking function parameter that's a reference
- reactjs - How to fix update Modal not showing this.state.value
- c++ - How to handle manipulators in my overloading <
I have class
class MyClass { public: .... friend ostream& operator<<(ostream& os, const MyClass& myobject); }; ostream& operator<&
- java - JVM crash - Dump Event "gpf" (00002000) received
- javascript - How to add a value of a variable to name of another one?
- kotlin - Jar made by gradle's jar task is not "fat" enough
- c++ - Generate C++ function automatically
- twitter-bootstrap - Button cannot be added to bootstrap 4 Popper content ?