python创建全为0的二维列表遇到的坑

        本来想着简单点,用列表乘法

m = n = 3
test = [[0] * m] * n
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]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

中南自动化学院至渝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值