嵌套列表追加

2024-09-29 05:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想用python缩短一段代码片段,却发现了下面代码的奇怪工作方式

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?

为什么附加到嵌套列表会附加到列表中的所有嵌套列表

所有嵌套列表是否都指向一个列表?如果有的话,名单的原件在哪里


Tags: tosample代码列表outputis方式this