矩阵元素以这种方式相加

Matrix elements addition with this way

我写这段代码是为了用这种方式添加元素我的问题是我想用更大的矩阵应用它

zz=[[1,2],[3,4]]
for i in range(len(zz[0])):
    x=zz[0][i]
    for i in range(len(zz[1])):
        xx=x+zz[1][i]
        print(xx)

输出将是:

z[0][0]+z[1][0]
z[0][0]+z[1][1]
z[0][1]+z[1][0]
z[0][0]+z[1][1]

你可以为此使用递归:

def sum_combinations(matrix):
    head, *tail = matrix
    if not tail:  # we reached the last row
        yield from head
        return
    for number in head:
        for other in sum_combinations(tail):
            yield number + other

这适用于任何大小的矩阵。

用法:

for sum_ in sum_combinations(zz):
    print(sum_)