Saturday, September 12, 2015

Python的几个注意事项

最近在研究python。发现了以下一些和matlab不太一样的部分。特立此存照。

1. Python里面,a=4,则a是整数,a=4.0,则a是浮点数。a=4,则a/3==1

2. 两个list,X=[1,2,3], Y=[1,2,3], X.append(4), Y.append(4),则X==[1,2,3,4], Y==[1,2,3,4]
但是: X=[1,2,3], Y=X, X.append(4), Y.append(4),则X==[1,2,3,4,4], Y==[1,2,3,4,4]

1 comment:

MoonKnight said...

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.