简体   繁体   English

深拷贝 Python 与整数 vs arrays

[英]Deep copy Python with integers vs arrays

Given the following code:给定以下代码:

x = y = z = 0
x = 10
print(y) // prints 0

x = y = z = [1, 2, 3, 4, 5]
x[0] = 10
print(y) // prints [10, 2, 3, 4, 5]

How come with simple integers Python does not perform a deep copy whilst with arrays it does?如何使用简单整数 Python 不执行深层复制,而使用 arrays 呢?

In the first example, you have three pointers pointing to a memory location for an integer.在第一个示例中,您有三个指针指向 integer 的 memory 位置。 Then you direct one of the pointers, X, to a different memory location.然后将其中一个指针 X 指向不同的 memory 位置。 The other two pointers continue to point to the original integer.另外两个指针继续指向原来的integer。 In the second example, you have three pointers pointing to a list.在第二个示例中,您有三个指向列表的指针。 The list is mutable.该列表是可变的。 Then you change one of the items in the list.然后您更改列表中的一项。 The three-pointers are still pointing to the same list and checking the value of any of them will return the same answer.三指针仍然指向同一个列表,检查其中任何一个的值都会返回相同的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM