写一个数据分析的程序,中间要处理一个2x3矩阵的相加,遂写出了下面的代码

def add(x, y):
    return x + y


def two_matrix_add(x, y):
    result = []
    for i in xrange(len(x)):
        result.append(tuple(map(lambda t: reduce(add, t), zip(x[i], y[i]))))
    return tuple(result)


def matrix_add(matrix_list):
    return reduce(two_matrix_add, matrix_list)

下面测试一下:

>>> matrix_1 = [
...     [0, 1, 2, 3],
...     [4, 5, 6, 7],
...     [8, 9, 10, 11]
... ]
>>> matrix_2 = [
...     [128, 204, 125, 66],
...     [230, 222, 186, 220],
...     [110, 86, 176, 249]
... ]
>>> matrix_3 = [
...     [189, 138, 188, 113],
...     [214, 85, 180, 217],
...     [126, 195, 203, 207]
... ]
>>> matrix_add([matrix_1, matrix_2])
((128, 205, 127, 69), (234, 227, 192, 227), (118, 95, 186, 260))
>>> matrix_add([matrix_1, matrix_2, matrix_3])
((317, 343, 315, 182), (448, 312, 372, 444), (244, 290, 389, 467))