Sunday, September 11, 2016

我应该多读一下评论……

MoonKnight在我一年前的一则post里说:

List, dictionary, set, tuple etc. are all objects (classes) in python. When copying an object in python, the default way is to do a "shallow copy". 
Basically x=y just copy the reference (or pointer if you are more familiar with C) of x to y, so now they point to the same address in your memory. Thus change one will automatically change the other.If you want a "deep copy" (a separate copy with a different memory address) for a list, you can do x=list(y). There is also a package called copy, with a function called deepcopy, so x=copy.deepcopy(y) should do the same.On the other hand, the difference of "shallow copy" and "deep copy" only exists for objects. If you are copying an integer, string, boolean etc. It can only create a deep copy.

我要是早点看到就没今天这个问题了……

Python的数组赋值问题

今天晚上写code遇到如下问题:

Code1:

a=0
b=6
while b!=a:
    a=b
    print a
    b=b-1
    print a
这段代码将陷入死循环,输出如下:
6
6
5
5
4
4
... 

Code2:
a=[0]
b=[6]
while b!=a:
    a=b
    print a
    b[0]=b[0]-1
    print a 
这段代码在第一个循环结束就停了,输出如下:
[6]
[5] 

这个网站有讨论。 主要原因是,python的list名字其实是一个指针。假设有两个list,分别为a和b,如果赋值a=b,并不是建立一个新的list a,使其内容跟b一样,而是将a和b同时指向一个list对象。

所以,如果有如下两个list:

a=[0,1]
b=[0,1]
# a==b: TRUE
# a is b: FALSE