A, b, c, d, a1, b1, c1和d1是对内存中对象的引用,它们由它们的id唯一标识。
An assignment operation takes a reference to the object in memory and assigns that reference to a new name. c=[1,2,3,4] is an assignment that creates a new list object containing those four integers, and assigns the reference to that object to c. c1=c is an assignment that takes the same reference to the same object and assigns that to c1. Since the list is mutable, anything that happens to that list will be visible regardless of whether you access it through c or c1, because they both reference the same object.
C1 =copy.copy(c)是一个“浅拷贝”,它创建一个新列表,并将对新列表的引用赋值给C1。C仍然指向原始的列表。所以,如果你在c1处修改列表,c所指向的列表不会改变。
复制的概念与整数和字符串等不可变对象无关。由于不能修改这些对象,因此不需要在内存的不同位置有相同值的两个副本。因此,整数和字符串,以及其他一些复制概念不适用的对象,只是简单地重新赋值。这就是为什么使用a和b的例子会得到相同的id。
c1=copy.deepcopy(c) is a "deep copy", but it functions the same as a shallow copy in this example. Deep copies differ from shallow copies in that shallow copies will make a new copy of the object itself, but any references inside that object will not themselves be copied. In your example, your list has only integers inside it (which are immutable), and as previously discussed there is no need to copy those. So the "deep" part of the deep copy does not apply. However, consider this more complex list:
E = [[1,2],[4,5,6],[7,8,9]]]
这是一个包含其他列表的列表(也可以将其描述为一个二维数组)。
If you run a "shallow copy" on e, copying it to e1, you will find that the id of the list changes, but each copy of the list contains references to the same three lists -- the lists with integers inside. That means that if you were to do e[0].append(3), then e would be [[1, 2, 3],[4, 5, 6],[7, 8, 9]]. But e1 would also be [[1, 2, 3],[4, 5, 6],[7, 8, 9]]. On the other hand, if you subsequently did e.append([10, 11, 12]), e would be [[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]]. But e1 would still be [[1, 2, 3],[4, 5, 6],[7, 8, 9]]. That's because the outer lists are separate objects that initially each contain three references to three inner lists. If you modify the inner lists, you can see those changes no matter if you are viewing them through one copy or the other. But if you modify one of the outer lists as above, then e contains three references to the original three lists plus one more reference to a new list. And e1 still only contains the original three references.
“深度复制”不仅会复制外部列表,而且还会进入列表内部并复制内部列表,因此两个结果对象不包含任何相同的引用(就可变对象而言)。如果内部列表中有更多的列表(或其他对象,如字典),它们也会被复制。这是“深层复制”的“深层”部分。