我编写此代码以这种方式添加元素,我的问题是我想将其应用于更大的矩阵
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_)