这个函数应该返回一个整数数组,它应该返回两个给定数组的总和,但无论我做什么,数组都不会返回预期的数组。
def printarr(arr_of_int):
for i in range(len(arr_of_int)):
for j in range(len(arr_of_int[0])):
print(arr_of_int[i][j],end="\t")
print()
#******************addarr function starts here********************
def addarr(arr1, arr2):
if len(arr1) == len(arr2) and len(arr1[0]) == len(arr2[0]):
final = [[0]*len(arr1)]*len(arr1[0])
# printarr(final)
for i in range(len(arr1)):
# iterate through columns
for j in range(len(arr1[0])):
final[i][j] = arr1[i][j] + arr2[i][j]
return final
else:
print("Input or data wrong.")
#Main Body
test1 = [[3,1,2],[1,3,0],[7,1,9]]
test2 = [[1,1,1],[1,1,1],[1,1,1]]
final = addarr(test1,test2)
printarr(final)
这给了我以下结果:
8 2 10
8 2 10
8 2 10
虽然我期待:
4 2 3
2 4 1
8 2 10
我在这里缺少什么?返回数组最终会出错吗?