[英]Python variable handling, I don't understand it
我無法找到關於這個非常簡單的程序中發生的事情的簡明信息:
print 'case 1'
# a and b stay different
a = [1,2,3]
b = a
b = [4,5,6]
print 'a =',a
print 'b =',b
print
print 'case 2'
# a and b becomes equal
a = [1,2,3]
b = a
b[0] = 4
b[1] = 5
b[2] = 6
print 'a =',a
print 'b =',b
print
print 'case 3'
# a and b stay different now
a = [1,2,3]
b = a[:]
b[0] = 4
b[1] = 5
b[2] = 6
print 'a =',a
print 'b =',b
print
print 'case 4'
# now the funny thing
a=[1,2,[3]]
b=a[:]
b[0] = 4
b[1] = 5
b[2][0] = 6 # this modifies b and a!!!
這個簡單測試的輸出是:
case 1
a = [1, 2, 3]
b = [4, 5, 6]
case 2
a = [4, 5, 6]
b = [4, 5, 6]
case 3
a = [1, 2, 3]
b = [4, 5, 6]
case 4
a = [1, 2, [6]]
b = [4, 5, [6]]
我顯然不明白python如何處理每個案例。 任何人都可以提供一個鏈接,以便我可以閱讀它,或者對正在發生的事情做一個簡短的解釋嗎?
非常感謝。
在其中運行您的代碼,一切都應該在一分鍾內變得清晰。
這里有兩件重要的事情:
當你發現a
和b
都被修改了,那就是因為它們都指向同一個對象。 您可以執行id(a)
和id(b)
來確認這一點。
關於例子,請注意a[:]
將創建一個新的對象,它是一個副本a
。 但是,它將是淺拷貝,而不是深拷貝。 這解釋了為什么在示例4中,您仍然可以修改a
和b
。 它們指向不同的列表對象,但是一個元素是由它們共享的另一個列表。
案例1:名稱b
反彈。
情況2: a
和b
綁定到同一個對象。
案例3:的淺拷貝a
必然b
。 列表不同,但列表中的對象是相同的。
情況4:的淺拷貝a
被綁定到b
,然后將對象中的一個被突變。
重新綁定不會發生變異,並且變異不會重新綁定。
print 'case 1'
# a and b stay different
a = [1,2,3]
b = a #At this point 'b' and 'a' are the same,
#just names given to the list
b = [4,5,6] #At this point you assign the name 'b' to a different list
print 'a =',a
print 'b =',b
print
print 'case 2'
# a and b becomes equal
a = [1,2,3] #At this point 'b' and 'a' are the same,
#just names given to the list
b = a
b[0] = 4 #From here you modify the list, since both 'a' and 'b'
#reference the same list, you will see the change in 'a'
b[1] = 5
b[2] = 6
print 'case 3'
# a and b stay different now
a = [1,2,3]
b = a[:] #At this point you COPY the elements from 'a' into a new
#list that is referenced by 'b'
b[0] = 4 #From here you modify 'b' but this has no connection to 'a'
b[1] = 5
b[2] = 6
print 'a =',a
print 'b =',b
print
print 'case 4'
# now the funny thing
a=[1,2,[3]]
b=a[:] #At this point you COPY the elements from 'a' into a new
#list that is referenced by 'b'
b[0] = 4 #Same as before
b[1] = 5
b[2][0] = 6 # this modifies b and a!!! #Here what happens is that 'b[2]' holds
#the same list as 'a[2]'. Since you only modify the element of that
#list that will be visible in 'a', try to see it as cases 1/2 just
#'recursively'. If you do b[2] = 0, that won't change 'a'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.