Python3.7--數(shù)據(jù)結(jié)構(gòu)--引用(Refer)

引用 (refer),如果有前幾天看我發(fā)的注意力test矩陣的輸出就應(yīng)該有注意到一個(gè)點(diǎn)就是我在產(chǎn)生隨機(jī)數(shù)就同時(shí)賦值給兩個(gè)數(shù)組。

image.png

這里引用如果只是賦值給另一個(gè)變量,應(yīng)該是地址引用,而不是重新申請(qǐng)一個(gè)地址空間存這個(gè)變量,所以你在對(duì)其中一個(gè)變量在操作時(shí)就會(huì)相互影響。
這點(diǎn)在編程時(shí)一定要注意。
接下來(lái)我們看幾個(gè)例子:

  • 賦值 變量mylist=shoplist
  • mylist.sort
  • mylist.append
  • 切片賦值 mylist_slice=shoplist[:]
  • 刪除 def mylist_slice[0]

print('Simple   Assignment')
shoplist    =   ['apple',   'mango',    'carrot',   'banana']
#   mylist  只是指向同一對(duì)象的另一種名稱
mylist  =   shoplist
print(mylist)
#['apple', 'mango', 'carrot', 'banana']
print(shoplist)
#['apple', 'mango', 'carrot', 'banana']
#進(jìn)行排序
mylist.sort();
print(mylist)
#['apple', 'banana', 'carrot', 'mango']
print(shoplist)
#['apple', 'banana', 'carrot', 'mango']
#增加一項(xiàng)
shoplist.append('pear')
print(mylist)
#['apple', 'banana', 'carrot', 'mango', 'pear']
print(shoplist)
#['apple', 'banana', 'carrot', 'mango', 'pear']

print('Copy by  making  a   full    slice')
#那需要如何賦值才不會(huì)這樣呢?
mylist_slice = shoplist[:];
print(mylist_slice);
print(shoplist);
#['apple', 'banana', 'carrot', 'mango', 'pear']

print("del 第一個(gè)項(xiàng)目")
del mylist_slice[0];
print(mylist_slice);
#['banana', 'carrot', 'mango', 'pear']
print(shoplist);
#['apple', 'banana', 'carrot', 'mango', 'pear']


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容