【发布时间】:2019-06-23 06:11:23
【问题描述】:
我只是想在 python 中缩短代码 sn-p 并遇到以下代码的奇怪工作方式。
sample = [[]] * 3
# OUTPUT - [[], [], []] - Simple enough to understand
sample[0].append(1)
# OUTPUT - [[1],[1],[1]] - Why is this happening?
sample[1].append(2)
# OUTPUT - [[1,2],[1,2],[1,2]] - Why is this happening?
sample[2].append(3)
# OUTPUT - [[1,2,3],[1,2,3],[1,2,3]] - Why is this happening?
为什么追加到嵌套列表会追加到列表中的所有嵌套列表?
所有嵌套列表都指向一个列表吗?如果是,列表的原始副本在哪里?
【问题讨论】:
标签: python python-3.x list append