ImportNumPy as NPdefBuild_chessboard (N): Chessboard=Np.zeros ((n,n))returnChessboarddefPrint_chessboard (chessboard): N=Len (chessboard) forRinchRange (N): forCinchRange (N):ifCHESSBOARD[R,C] = = 1: Print('Q', end="") Else: Print('.', end="") Print () Print ()#generate an empty 4x4 chessboard:Chessboard = Build_chessboard (4)Print(chessboard)#Place 4 non-attacking Queens in this boardchessboard[1,0] = 1chessboard[3,1] = 1Chessboard[0,2] = 1chessboard[2,3] = 1#pretty print the resulting boardPrint_chessboard (chessboard)defTest (CB): cb[0, 0]= 1Print_chessboard (CB) Chessboard= Build_chessboard (4) Print_chessboard (chessboard) test (Chessboard.copy ())#try Chessboard.copy () insteadPrint_chessboard (Chessboard)#oooops!defTest (b): b= B + 1Print(b) n= 1Print(n) test (n)Print(n)ImportCopydefTest (b): B.append (1) Print(b) n= [1, 2, 3]Print(n) test (copy.copy (n) )Print(n) test (n)Print(n) a=[]copy.deepcopy (a)ImportCopy#copy makes a copy of the Outer-most object, but keeps the same references to the inner#object.A=[2,4,[6]]Print("before:a=", a) b=Copy.copy (a) b[0]+=1b[2][0]+=1Print("after:a="A"b="B"(using copy)")#Deepcopy also makes a copy of each contained element (recursively)A=[2,4,[6]]b=Copy.deepcopy (a) b[0]+=1b[2][0]+=1Print("after:a="A"b="B"(using deepcopy)")
To summarize: The function call can not change the original value (similar to the time the value is passed), but can change the original list (append). Deepcopy is safer than copy because no inner reference (copy, inner reference may cause inner layer values to be modified)
Problems with Python----function call values