比较以下两种数组初始化:
arr1 = [[0]*5]*5
arr2 = [[0 for i in range(5)] for j in range(5)]
乍看都是初始化一个5*5的二维数组,但若都执行相同的赋值语句后,结果却大不一样:
arr1[0][0] = 1 # arr1会变为[[1,0,0,0,0],[1,0,0,0,0],[1,0,0,0,0],[1,0,0,0,0],[1,0,0,0,0]]
arr2[0][0] = 1 # arr2会变为[[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
下图解释了arr1的初始化和赋值的逻辑
arr1初始化 arr1赋值
网友评论