0
def addM(a, b):
    res = []
    for i in range(len(a)):
        row = []
        for j in range(len(a[0])):
            row.append(a[i][j]+b[i][j])
        res.append(row)
    return res

I found this code here which was made by @Petar Ivanov, this code adds two matrices, i really don't understand the 3rd line, why does he use len(a) and the 5th line, why does he use len(a[0]). In the 6th line, also why is it a[i][j] +b[i][j]?

4

1 回答 1

2

The matrix here is a list of lists, for example a 2x2 matrix will look like: a=[[0,0],[0,0]]. Then it is easy to see:

  1. len(a) - number of rows.
  2. len(a[0]) - number of columns (since this is a matrix, the length of a[0] is the same as length of any a[i]).
  3. This way, i is the number of row, j is the number of column and a[i][j]+b[i][j] is simply adding up the elements of two matrices which are placed in the same locations in the matrices.

For all this to work, a and b should be of the same shapes (so, numbers of rows and columns would match).

于 2013-11-11T00:50:58.803 回答