Python中的矩阵加法-列表 [英] Matrix Addition in Python - list

查看:92
本文介绍了Python中的矩阵加法-列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python编写Matrix Addition函数.

I'm trying to write Matrix Addition function using Python.

这是我一直在尝试的代码,但是它给了我一个列表索引错误,我不知道为什么.

Here is the code I've been trying, but it gives me a list index error and I cannot figure out why.

def matrixADD(A,B):
Z = []
#TODO
for i in range(0,len(A)):
    for column in range(0, len(A)):
        result = A[i][column] + B[i][column]
        Z[i][column] = (result)
return Z

使用以下列表:

A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]

因此,从理论上讲,A [0] [0] + B [0] [0]等于5,我想将该值添加到位置Z [0] [0].

So in theory, A[0][0] + B[0][0] would equal 5, and I would want to add that value to position Z[0][0].

但是我一直收到错误:IndexError:列表索引超出范围

However I keep receiving the error: IndexError: list index out of range

推荐答案

>>> A = [[2,4], [7,0], [6,3]]
>>> B = [[3,1], [-1,8], [-3, 3]]
>>> Z = [map(sum, zip(*t)) for t in zip(A, B)]
>>> Z
[[5, 5], [6, 8], [3, 6]]

关于如何解决当前代码:

As for how you could fix your current code:

Z = []
for i in range(len(A)):
    row = []
    for j in range(len(A[i])):
        row.append(A[i][j] + B[i][j])
    Z.append(row)

这里重要的部分是,除非该行/列已经存在,否则您不能仅将其分配给Z[i][j],因此您需要分别构造每个内部列表并将它们附加到Z.另外,内部循环需要以一行的长度结尾,因此我将range(len(A))更改为range(len(A[i])).

The important parts here being that you cannot just assign to Z[i][j] unless that row/column already exists, so you need to construct each inner list separately and append them to Z. Also the inner loop needs to end at the length of a row, so I changed range(len(A)) to range(len(A[i])).

这篇关于Python中的矩阵加法-列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆