Question in Python matrix calculation. The value changes to the same for the items that are not selected.

Asked 2 years ago, Updated 2 years ago, 16 views

def sumMatrix(A,B):
    answer = [[0]*len(A[0])]*len(A)

    for i in range(len(A)):
        for j in range(len(A[0])):
            a=A[i][j]+B[i][j]
            answer[i][j]=a
            print(answer)
            print(i,j,a,answer[i][j],A[i][j],B[i][j])
    return answer

print(sumMatrix([[1,2], [2,3]], [[3,4],[5,6]]))

Results

[[4, 0], [4, 0]]
0 0 4 4 1 3
[[4, 6], [4, 6]]
0 1 6 6 2 4
[[7, 6], [7, 6]]
1 0 7 7 2 5
[[7, 9], [7, 9]]
1 1 9 9 3 6
[[7, 9], [7, 9]]

I don't know why the answer[1][0] changes, instead of just the answer[0][0] value. Please help me

python

2022-09-21 22:55

1 Answers

It's a self-answer. In this case, Python is an int data type, but reference copy is made.


2022-09-21 22:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.