更改副本的值也会更改原始文件的值

时间:2019-12-04 15:52:48

标签: python list variables copy

更改变量b的值(它是a的副本)也会更改a的值。

a = [[0]]
b = a.copy()

print("a before", a)

b[0][0] = 1

print("a after ", a)

打印:

a before [[0]]
a after  [[1]]

尽管可行:

a = [0]
b = a.copy()

print("a before", a)

b[0] = 1

print("a after ", a)

打印:

a before [[0]]
a after  [[0]]

1 个答案:

答案 0 :(得分:0)

关闭副本。深层复制有效。

import copy

a = [[0]]
b = copy.deepcopy(a)

print("a before", a)

b[0][0] = 1

print("a after ", a)

打印:

a before [[0]]
a after  [[0]]