說
list1=[4,8,12]
a,b,c=list1
輸出是a=4,b=8,c=12。
我的困惑
導師告訴我們,這是不喜歡a被映射到4,b到8和c到12。我沒明白他說的清楚(雖然我反復聽他多次)。他告訴像物件的創建4和a映射到4。但是這和我在下面的圖中展示的有什么區別?

uj5u.com熱心網友回復:
關于你的照片是真實誤導事情是,它意味著a,b和c參考片list1。如果更改list1,不過,你會發現a,b和c不受這種變化。
繪制圖片的更好方法可能是將 4、8 和 12 與 分開顯示list1:
list1-->[ ][ ][ ]
| | |
V V V
4 8 12
^ ^ ^
| | |
a b c
所有的變數都是相互獨立的,即使它們中的一些(例如list1[0]和a)當前指向相同的值。
換句話說:saya = list1[0]是說“評估list1[0]并分配a參考該值現在的任何值”,這與說“makea成為”的別名不同list1[0]。
uj5u.com熱心網友回復:
嘗試這個:
# define the list
list1=[4,8,12]
# reserve 3 memory spaces and unpack the values from list into them
# those memory spaces will contain one integer each one of the size of
# sys.getsizeof(int()) == 28 bytes (Python 3)
# a,b and c are actually pointers to those memory spaces
a,b,c=list1
print(a,b,c)
# change the first value of the list
list1[0] = 56
print(list1)
# now check that indeed "a" is not the same pointer than "list1[0]"
print(a)
但
你必須小心這種帶有串列的分配,也試試這個:
list2 = list1
print(list1, list2)
# then change any of them
list1 [0] = -1
# check that "list2" is now pointing to the same memory address than list1
print(list1, list2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365131.html
標籤:Python
上一篇:如何從字典創建不同的資料框
