Operation result by-Value or by-Reference [Python]

对一个对象的操作使这个对象有所变化。
这种情况很常见,比如“去除一个list的后三个元素”。
我首先想到的方法是:

>>> a = [1,2,3,4,5,6,7]
>>> a = a[:-3]
>>> a
[1, 2, 3, 4]
>>>

这样的确能使a得到想要的改变,但实际上a“已经不是原来那个a”了。

>>> id(a)
20363584
>>> a = a[:-3]
>>> id(a)
20365224

a所代表的对象已经不同。id函数可以得到对象的标识(identify),从而区别不同对象。

这种情况有时会产生很致命的错误。比如a作为参数传递给一个函数,因为Python的函数参数调用是“引用传值,pass-by-reference”的,所以可能希望函数内对a的操作影响到函数外a对象,这时上面的情况就会发生错误。
正是这个错误耽误了我半天的时间来debug。
针对不同的对象,解决这个的问题方法不同。仅对这里提出的问题做个正解:

>>> a = [1,2,3,4,5,6,7]
>>> id(a)
14198904
>>> del a[-3:]
>>> id(a)
14198904
>>> a
[1, 2, 3, 4]

这个问题的最根本问题其实出在

>>> a = a[:-3]

这句。“=”默认的意思是“赋值,pass the value”,不是传递对象的引用。

list partterns in Matlab and Python

list partterns in Matlab and Python

A comparation between usage in Matlab against Python of the List variable as the most common and frequently utility in the languages.

Indexing

Key point of Indexing: Index, List to be filtered
Matlab

>> lst = rand(2,3) %@ the List to be filtered
lst =
0.4103 0.0579 0.8132
0.8936 0.3529 0.0099

>> i = lst > 0.5 %@ the Index, a list with integer elements
i =
0 0 1
1 0 0

>> lst(i) %@ the Result, get a new list from lst with elements indexed by i
ans =
0.8936
0.8132

>> lst(lst>0.5)=1
lst =
1.0000 0.0579 1.0000
1.0000 1.0000 0.0099

Append

Python

lst.append(obj)

Matlab
No declaration or additional appending operation.

>> clear
>> lst(2) = 1
lst =
0 1

>> lst(5) = 1
lst =
0 1 0 0 1

>> lst(length(lst)+1) = 9 %@ Appending operation
lst =
0 1 0 0 1 9

Sorting

>> lst=rand(3,4)
lst =
0.9501 0.4860 0.4565 0.4447
0.2311 0.8913 0.0185 0.6154
0.6068 0.7621 0.8214 0.7919
>> sort(lst) %@ Matrix sorting means “Sorts each column”.
ans =
0.2311 0.4860 0.0185 0.4447
0.6068 0.7621 0.4565 0.6154
0.9501 0.8913 0.8214 0.7919
>> sortrows(lst,1) %@ Each row treated as a element in List.
ans =
0.2311 0.8913 0.0185 0.6154
0.6068 0.7621 0.8214 0.7919
0.9501 0.4860 0.4565 0.4447

Test Zoundry

A test of Zoundry. Noticed that it’s built up by Python. A Tag could be added and what will happen?

Del.icio.us :

Random posts

  • 党委、政府PK不过黑恶社会?(转载自人民网)
  • Difference between Redirect and CNAME
  • Implementing Slope-One in T-SQL
  • 关于高勤荣的一些文章和报道
  • 心有灵犀啊