【问题标题】:Nested list append [duplicate]嵌套列表追加[重复]
【发布时间】: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


    【解决方案1】:

    是的,所有嵌套列表都指向一个列表。

    如果是,列表的原始副本在哪里?

    不知道你在问什么。每个嵌套列表都指向原始列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多