chainsawriot

Home | About | Archive

Python confusion #1

Posted on Feb 28, 2011 by Chung-hong Chan

Python:

horsemen = ["war", "famine", "pestilence", "stupidity"]
good = horsemen
print good
horsemen[3] = "death"
print good

結果是 ['war', 'famine', 'pestilence', 'death']

R

horsemen < - c("war", "famine", "pestilence", "stupidity")
good <- horsemen
print(good)
horsemen[4] <- "death"
print(good)

[1] "war" "famine" "pestilence" "stupidity"

Python 只叫 good = horsemen 為 aliasing ((How to Think Like a Computer Scientist section 8.11)) 。如果想 Python 像是 R 那樣,要用的功能叫 list cloning 。

horsemen = ["war", "famine", "pestilence", "stupidity"]
good = horsemen[:]
print good
horsemen[3] = "death"
print good

Powered by Jekyll and profdr theme