1 回答
TA贡献1810条经验 获得超4个赞
如果一个列表(或其他可变容器)被添加到一个列表中,并且该列表稍后发生变异,则该变异也将应用于该容器,因为它是同一个列表。如果存在后期突变的风险,请传递(或存储)列表的副本以防止此类问题(称为别名)。
# A function that accepts a list and changes it
>>> def f(sts):
... sts[-1] = sts[-1] * 2
... return [x for x in sts]
...
>>> sts = [1]
>>> out = []
# Observe how the _out_ list is not what we expect (ascending powers of two)
>>> for i in range(5):
... sts = f(sts)
... out.append(sts)
... print(out)
...
[[2]]
[[4], [4]]
[[4], [8], [8]]
[[4], [8], [16], [16]]
[[4], [8], [16], [32], [32]]
# If we pass a copy of sts, we get the expected output.
>>> sts = [1]
>>> out = []
>>> for i in range(5):
... sts = f(sts[:])
... out.append(sts)
... print(out)
...
[[2]]
[[2], [4]]
[[2], [4], [8]]
[[2], [4], [8], [16]]
[[2], [4], [8], [16], [32]]
添加回答
举报