在python中添加两个矩阵
我正在尝试编写一个添加两个矩阵的函数来通过以下文档测试:
>>> a = [[1, 2], [3, 4]]
>>> b = [[2, 2], [2, 2]]
>>> add_matrices(a, b)
[[3, 4], [5, 6]]
>>> c = [[8, 2], [3, 4], [5, 7]]
>>> d = [[3, 2], [9, 2], [10, 12]]
>>> add_matrices(c, d)
[[11, 4], [12, 6], [15, 19]]
所以我编写了一个函数:
def add(x, y):
return x + y
然后我编写了以下函数:
def add_matrices(c, d):
for i in range(len(c)):
print map(add, c[i], d[i])
我排序得到了正确的答案。
I'm trying to write a function that adds two matrices to pass the following doctests:
>>> a = [[1, 2], [3, 4]]
>>> b = [[2, 2], [2, 2]]
>>> add_matrices(a, b)
[[3, 4], [5, 6]]
>>> c = [[8, 2], [3, 4], [5, 7]]
>>> d = [[3, 2], [9, 2], [10, 12]]
>>> add_matrices(c, d)
[[11, 4], [12, 6], [15, 19]]
So I wrote a function:
def add(x, y):
return x + y
And then I wrote the following function:
def add_matrices(c, d):
for i in range(len(c)):
print map(add, c[i], d[i])
And I sort of get the right answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
矩阵库
您可以使用 numpy 模块,它对此提供支持。
本土解决方案:重量级
假设您想自己实现它,您需要设置以下机制,它可以让您定义任意成对运算:
现在添加成对方法就像馅饼一样简单:
示例:
您甚至可以添加成对求幂、求反、二元运算等。我在这里不进行演示,因为最好将 * 和 ** 留给矩阵乘法和矩阵求幂。
自制解决方案:轻量级
如果您只想以一种非常简单的方式将操作映射到仅两个嵌套列表矩阵,您可以这样做:
演示:
通过附加的 if-else 和关键字参数,您可以在 lambda 中使用索引。下面是如何编写矩阵行序枚举函数的示例。为了清楚起见,上面省略了 if-else 和关键字。
edit
所以我们可以像这样编写上面的
add_matrices
函数:演示:
Matrix library
You can use the
numpy
module, which has support for this.Home-grown solution: heavyweight
Assuming you wanted to implement it yourself, you'd set up the following machinery, which would let you define arbitrary pairwise operations:
Now adding pairwise methods is as easy as pie:
Example:
You can even add pairwise exponentiation, negation, binary operations, etc. I do not demonstrate it here, because it's probably best to leave * and ** for matrix multiplication and matrix exponentiation.
Home-grown solution: lightweight
If you just want a really simple way to map an operation over only two nested-list matrices, you can do this:
Demo:
With an additional if-else and keyword argument, you can use indices in your lambda. Below is an example of how to write a matrix row-order
enumerate
function. The if-else and keyword were omitted above for clarity.edit
So we could write the above
add_matrices
function like so:Demo:
另一种解决方案:
One more solution:
但正如上面所说,没有必要重新发明轮子,只需使用
numpy
,这可能会更快、更灵活。But as said above, there is no need to reinvent the wheel, just use
numpy
, which is likely to be faster and more flexible.