2012-02-23 11 views
6

を理解していない私は、この非常に単純なプログラムで何が起こっているのかについての簡潔な情報を見つけることができません。Pythonの変数の取り扱い、私はそれを

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がそれぞれのケースを処理するのか分かりません。私はそれについて読むことができるように、または何が起こっているのかの短い説明を提供することができますか?

ありがとうございます。

答えて

6

ここでは二つの重要な事柄があります。

  • 変数がちょうどオブジェクト
  • 一覧を指してラベルされているが、Pythonで変更可能であり、整数ではありません。

あなたは両方abが変更されていることを見つけた場合、それらの両方が同じオブジェクトを指しているので、それはです。これを確認するにはid(a)id(b)を行うことができます。

例に関しては、a[:]aのコピーである新しいオブジェクトを作成することに注意してください。ただし、深いコピーではなく、浅いコピーになります。これは、例4では、なぜabの両方を変更できるのかを説明しています。彼らは別のリストオブジェクトを指していますが、1つの要素は両方の要素によって共有される別のリストです。

4

ケース1:名前bがリバウンドです。

ケース2:abは、同じオブジェクトにバインドされています。

ケース3:aの浅いコピーがbにバインドされています。リストは異なりますが、リスト内のオブジェクトは同じです。

ケース4:aのシャローコピーはbにバインドされ、オブジェクトの1つが変更されます。

再結合が変異していない、と変異が再バインドされません。

3
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' 
+0

優れた説明。これは私を非常に助け、特にlist [:]ステートメント。ありがとう。 – trinkner

関連する問題