以这种方式添加矩阵元素

问题描述 投票:0回答:1

我编写此代码以这种方式添加元素,我的问题是我想将其应用于更大的矩阵

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]
python-3.x matrix addition
1个回答
0
投票

您可以为此使用递归:

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_)
© www.soinside.com 2019 - 2024. All rights reserved.