#!/usr/bin/python
# Filename: reference.py
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
(源文件:code/reference.py)
輸出
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
它如何工作
大多數(shù)解釋已經在程序的注釋中了。你需要記住的只是如果你想要復制一個列表或者類似的序列或者其他復雜的對象(不是如整數(shù)那樣的簡單 對象 ),那么你必須使用切片操作符來取得拷貝。如果你只是想要使用另一個變量名,兩個名稱都 參考 同一個對象,那么如果你不小心的話,可能會引來各種麻煩。
給 Perl 程序員的注釋
記住列表的賦值語句不創(chuàng)建拷貝。你得使用切片操作符來建立序列的拷貝。