1

我试图用 zip 函数和循环来解决这个问题:

mat_C=[[] for i in range(NO_OF_ROWS_C)]
for i in range(NO_OF_ROWS_C):
    for j in range(NO_OF_COLUMNS_C):
        mat_C=[a+b for (a,b) in zip(mat_A,mat_B)]
for i in range(NO_OF_ROWS_C):
    for j in range(NO_OF_COLUMNS_C):
        print(mat_C[i][j])
4

2 回答 2

2

NumPy对于这类事情非常有用。特别是,NumPy 数组的添加是按元素执行的。

mat_A = np.asarray(mat_A)
mat_B = np.asarray(mat_B)
mat_C = mat_A + mat_B
print(mat_C)

没有numpy,

mat_C = [[a+b for a,b in zip(row_A, row_B)] for row_A, row_B in zip(mat_A, mat_B)]
于 2013-05-02T12:31:20.023 回答
1
>>> A = [[1, 2], [3, 4]]
>>> B = [[5, 6], [7, 8]]
>>> [[c+d for c, d in zip(a, b)] for a, b in zip(A,B)]
[[6, 8], [10, 12]]

numpy

>>> import numpy as np
>>> A = np.array([[1, 2], [3, 4]])
>>> B = np.array([[5, 6], [7, 8]])
>>> A + B
array([[ 6,  8],
       [10, 12]])
于 2013-05-02T12:31:52.123 回答