【发布时间】: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