python创建全为0的⼆维列表遇到的坑
本来想着简单点,⽤列表乘法
m = n =3
test =[[0]* m]* n令数组全部的值为0
print(test)
输出也看了⼀下,没啥问题
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
m = n =3
test =[[0]* m]* n
print(test)
test[0][0]=2
print(test)
输出就变得奇怪了
[[0,0,0],[0,0,0],[0,0,0]]
[[2,0,0],[2,0,0],[2,0,0]]
Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers;
consider:
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
也就是说matrix = [[array]] * 3操作中,只是创建3个指向array的引⽤,所以⼀旦array改变,matrix中3个list也会随之改变。
⽰例1 正确的做法
dp =[[0]*(3)for _ in range(3)]
print(dp)
dp[0][0]=4
print(dp)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[4, 0, 0], [0, 0, 0], [0, 0, 0]]
⽰例2 错误的做法
dp =[[0,0,0]]*3
print(dp)
dp[0][0]=4
print(dp)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] [[4, 0, 0], [4, 0, 0], [4, 0, 0]]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论