Python对象混淆:a=b,修改b和a变化! [英] Python objects confusion: a=b, modify b and a changes!
问题描述
直到今晚我才知道 Python.做这样的事情的正确方法是什么?这是我的代码:
a = ["一", "二", "三"]b = a # 这里我想要一个完整的副本,当 b 改变时,对 a 绝对没有影响b.append["四"]print a # a 现在有四"
基本上我想知道,而不是 b = a
步骤,我将如何正确制作列表或字典的副本,以便在 b
更改时a
不会随之改变吗?
您遇到的是引用的概念.Python 中的所有对象都有一个引用,当你为 a
和 b
分配一到两个名称时,这会导致 a
和 b
指向 same 对象.
使用列表,您可以使用 b = a[ 创建一个新列表
.b
,它是另一个 a
的副本:]
对于任何对象的更通用的解决方案,请使用复制模块.浅拷贝将复制您正在复制的对象中存储的引用,而深拷贝将递归地创建所有对象的新副本.
<预><代码>>>>a = [范围(2),范围(3)]>>>b = copy.copy(a) # a 的浅拷贝,等价于 a[:]>>>b[0] = 范围(4)>>>a, b # 设置 b 的元素使 a 保持不变([[0, 1], [0, 1, 2]], [[0, 1, 2, 3], [0, 1, 2]])>>>b[1].append(3)>>>a, b # 修改 b 的元素会修改 a 中的元素([[0, 1], [0, 1, 2, 3]], [[0, 1, 2, 3], [0, 1, 2, 3]])>>>a = [范围(2),范围(3)]>>>b = copy.deepcopy(a) # a 的深度递归副本>>>b[1].append(3)>>>a, b # 修改 b 中的任何内容都会保持 a 不变([[0, 1], [0, 1, 2]], [[0, 1], [0, 1, 2, 3]])I thought i knew Python until tonight. What is the correct way to do something like this? Here's my code:
a = ["one", "two", "three"]
b = a # here I want a complete copy that when b is changed, has absolutely no effect on a
b.append["four"]
print a # a now has "four" in it
Basically i want to know, instead of the b = a
step, how would I correctly make a copy of a list or dictionary so that when b
is changed a
does not change along with it?
What you are experiencing is the concept of references. All objects in Python have a reference and when you assign one to two names a
and b
, this results in both a
and b
pointing to the same object.
>>> a = range(3)
>>> b = a # same object
>>> b.append(3)
>>> a, b # same contents
([0, 1, 2, 3], [0, 1, 2, 3])
With lists, you can make create a new list b
that is a copy of another a
using b = a[:]
.
>>> a = range(3)
>>> b = a[:] # make b a new copy of a
>>> b.append(3)
>>> a, b # a is left unchanged
([0, 1, 2], [0, 1, 2, 3])
For a more general solution for any object, use the copy module. A shallow copy will copy the references stored within the object you're copying, whereas a deep copy will recursively make new copies of all objects.
>>> a = [range(2), range(3)]
>>> b = copy.copy(a) # shallow copy of a, equivalent to a[:]
>>> b[0] = range(4)
>>> a, b # setting an element of b leaves a unchanged
([[0, 1], [0, 1, 2]], [[0, 1, 2, 3], [0, 1, 2]])
>>> b[1].append(3)
>>> a, b # modifying an element of b modifies the element in a
([[0, 1], [0, 1, 2, 3]], [[0, 1, 2, 3], [0, 1, 2, 3]])
>>> a = [range(2), range(3)]
>>> b = copy.deepcopy(a) # deep recursive copy of a
>>> b[1].append(3)
>>> a, b # modifying anything in b leaves a unchanged
([[0, 1], [0, 1, 2]], [[0, 1], [0, 1, 2, 3]])
这篇关于Python对象混淆:a=b,修改b和a变化!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!