浅拷贝与Python中的深层拷贝

时间:2013-10-28 11:39:47

标签: python

我不知道为什么q充当指针。最终名单L是:[13, [28, [24, [3, None]]]]

我不明白如何添加[3, None]

import sys;

def main( argv=sys.argv ) :

        L = [24, None]

        t = [13, None]
        t[1] = L

        L = t
        t = [28, None]


        t[1] = L[1]
        L[1] = t

        t = [3, None]


        p = L
        while p != None :
                q = p
                p = p[1]

        if p == L :
                L = t
        else :
                q[1] = t

        print L

if __name__ == "__main__" :   
        main()

2 个答案:

答案 0 :(得分:1)

在你做的时候

if p == L:
    L = t
else: 
    q[1] = t

q实际上是指针[24, None],然后你执行了q[1] = t,因此它将成为[24, [3, None]]

此时,L实际上是[13, [28, q]]

所以它会改变你的L

中最内部的列表

答案 1 :(得分:1)

列表包含对象的引用。如果这些对象是可变的,那么当可变对象发生变化时,列表似乎会发生变化。实际上,列表不会改变,只是被引用对象的内容。您可以使用id()命令查看引用,并查看它们不会更改。

您的代码正在改变原始的[24, None]列表。这里有一些额外的print语句来查看发生了什么:

L = [24, None]    # Creates a list, which is a mutable object
print(id(L))      # Here is its unique ID.
t = [13, None]
t[1] = L
L = t
t = [28, None]
t[1] = L[1]
L[1] = t

print(L,id(L[1][1])) # Current contents of L, contains the same mutable list

t = [3, None]
p = L
while p:
    q = p         # q = [13, [28, [24, None]]], [28, [24, None]], [24, None]
    p = p[1]      # p = [28, [24, None]]      , [24, None]      , None

print(L,id(L[1][1])) # Here is L again, still contains the same mutable list
print(q,id(q))       # q also references the same mutable list

if p == L:        # False
    L = t
else:
    q[1] = t      # Mutate that same list!

print(L)

以下输出。请注意,[24, None]列表在所有情况下都具有相同的ID,因此当您更改None中的q元素时,L会引用相同的列表并显示为也改变了。

64809160
[13, [28, [24, None]]] 64809160
[13, [28, [24, None]]] 64809160
[24, None] 64809160
[13, [28, [24, [3, None]]]]

这是一个更简单的例子:

>>> q = [1,2,3]  # Create a list named 'q'
>>> L = [24, q]  # Put that list in L
>>> L
[24, [1, 2, 3]]
>>> q[1] = 5     # change 'q'
>>> L            # L appears to change. It references the same list.
[24, [1, 5, 3]]