0

我不知道为什么 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()
4

2 回答 2

1

当你在做的时候

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

q其实就是指针,也就是[24, None],然后你执行q[1] = t了,就变成了[24, [3, None]]

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

所以它会改变你 L 中最内部的列表

于 2013-10-28T11:50:25.167 回答
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元素时qL具有对相同列表的引用并且似乎也发生了变化。

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]]
于 2013-10-28T11:59:28.637 回答