hoamon's sandbox
hoamon
hoamon's sandbox is about »
tag cloud
- aix
- ajax
- amazon web service
- amd64
- android
- apache
- apple
- athletes
- bank
- baseball
- bike
- bitbucket
- blog
- bond
- book
- boto
- brooks
- bullshit
- capital gains tax
- car accident
- cds
- chrome
- civil engineering
- cloud computing
- cmclass
- computer
- construction management
- construction site management
- django
- drbl
- e-sun bank
- ec2
- eclipse
- ecryptfs
- education
- election
- english
- environment
- fedora
- feeling
- finance
- firefox
- firegpg
- flash ram
- foclass
- football
- fortran
- freetds
- future
- genetic algorithm
- glassfish
- gnuplot
- google adsense
- google app engine
- google gears
- gpg
- graphviz
- gtalk
- hg
- history
- htc
- html5
- http
- https
- ibm
- iconv
- ie
- iis
- iloveit
- imagemagick
- infomation
- investment
- ipatbles
- ipp2p
- iptables
- ironman
- java
- javascript
- job
- jog
- joke
- jpg
- jquery
- jython
- kde
- knapsack problem
- latex
- learning
- least square method
- levenberg-marquardt method
- libsvm
- linux
- list
- lp
- mac
- marathon
- math
- matlab
- mencoder
- mercurial
- microsoft
- mod_fcgi
- mod_python
- modelviz
- moinmoin
- monte carlo
- movie
- mplayer
- msn
- mssql
- mysql
- netbeans
- netfilter
- newton's method
- nfl
- nginx
- odiogo
- offline system
- open source
- openid
- openoffice
- openssl
- option
- oracle
- p2p
- paypal
- pdf2jpg
- pdftojpg
- perl
- personal
- pgp
- php
- policy
- politic
- postgresql
- power
- program
- python
- python25
- r51
- rds
- realty
- reit
- restructured text
- ruby
- ruby on rails
- s3
- science
- screen
- securities
- seediq bale
- self-management
- shell script
- sis
- skype
- solaris
- something
- ssh
- ssl
- subversion
- sun
- swap
- sybase
- tax
- testcase
- the guass-newton method
- the steepest descent method
- thinkpad
- tomcat6
- tortoisehg
- totero
- trac
- travel
- triathlete
- turbogears
- ubuntu
- un*x
- unix
- vedio
- version control
- vim
- virtual machine
- virtualbox
- vst
- web
- windows
- x86_64
- yahoo
- zfs
- zipcode
- zotera
- zotero
» python trick: 可變物件應用在簡寫的賦值表示式上
我在Python: 可變物件(list、hash)在 def 函式的引數傳遞部份有著特別的行為已經談過可變物件在函式傳址時的特別行為。
再來談談在簡寫的賦值表示式時,會遇到的陷阱。我們利用 a = b = [] 表示式來作到 a = []; b = []; 應用如下:
1 if __name__ == '__main__':上式結果為:
2 a = b = []
3 for i in range(1,3):
4 a.append(i)
5 b.append(2 * i)
6 print 'a: %s' % a
7 print 'b: %s' % b
a: [1, 2, 2, 4]
b: [1, 2, 2, 4]
是不是和你想的:
a: [1, 2]
b: [2, 4]
不一樣。
原因在於使用 a = b = [] 時,它也表示 a = b ,而又因為你賦給它們的值是一個可變物件 [] ,所以 a 實際上得到的是 b 的記憶體位址。於是你改變 a ,同時也改變了 b ,改變了 b ,也改變了 a 。







