【问题标题】:python: input variable of function append changes while changing host-variable [duplicate]python:函数追加的输入变量在更改主机变量时发生更改[重复]
【发布时间】:2019-10-01 12:51:20
【问题描述】:

在 python 中使用函数 append 时,我面临着(至少对我而言)某种奇怪的行为。在以下示例中,变量 growth 附加了变量 static 的值。然后 growth 中的一个值被改变,它也影响变量 static。为什么会这样?我认为 static 不应该改变,直到我分配一个新值,例如用'static = ...'。

在 Linux 上使用 Python 3.7.4(默认,2019 年 7 月 16 日,07:12:58)[GCC 9.1.0] 测试

代码:

static = {"a": 100, "b": 200}
growing = []
print("static", static)
print("growing", growing)
growing.append(static)
growing[0]["a"] = 999
print('after append and change in growing:')
print("static", static)
print("growing", growing)

这是我得到的输出:

static {'a': 100, 'b': 200}
growing []
after append and change in growing:
static {'a': 999, 'b': 200}
growing [{'a': 999, 'b': 200}]

【问题讨论】:

  • 因为growing[0] is static;您将该字典的 reference 附加到列表中。您可能会发现 nedbatchelder.com/text/names.html 很有用。
  • growing[0]static 指向同一个底层对象

标签: python python-3.x


【解决方案1】:
static = {"a": 100, "b": 200}

上面的语句在内存中创建了一个dict对象,变量“static”指向它。

growing.append(static)

当您将 static 附加到 grow 时,列表的第一个元素指向内存中的同一个 dict 对象。没有创建新对象,只有 2 个变量 static 和 grow[0] 指向内存中的同一个对象。因此,当这个 dict 被改变时

growing[0]["a"] = 999

你会看到两个变量的变化

【讨论】:

  • 感谢所有答案和 cmets。作为一个 Matlab 的老用户,这对我来说是全新的。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
相关资源
最近更新 更多