0

変数が2次元のファイル「data.imputation」を読み込んでいます'x'。変数'y'はのコピーです'x'。から最初の配列をポップします'y'(yは2Dです)。変更が反映されるのはなぜxですか?(からの最初の配列'x'もポップされます)

ip = open('data.meanimputation','r')
x = pickle.load(ip)
y = x
y.pop(0)

開始時に、len(x) == len(y)。後もy.pop(0)len(x) == len(y)。何故ですか?そして、どうすればそれを回避できますか?

4

2 に答える 2

3

y = x[:]の代わりに使用しy = xます。両方をy = x意味し、現在は同じオブジェクトを指しています。yx

次の例を見てください。

>>> x=[1,2,3,4]
>>> y=x
>>> y is x
True          # it means both y and x are just references to a same object [1,2,3,4], so changing either of y or x will affect [1,2,3,4]
>>> y=x[:]     # this makes a copy of x and assigns that copy to y,
>>> y is x     # y & x now point to different object, so changing one will not affect the other.
False

x がリストの場合、リストのリストは役に立ち[:]ません:

>>> x= [[1,2],[4,5]]
>>> y=x[:]   #it makes a shallow copy,i.e if the objects inside it are mutable then it just copies their reference to the y
>>> y is x
False         # now though y and x are not same object but the object contained in them are same 
>>> y[0].append(99)
>>> x
[[1, 2, 99], [4, 5]]
>>> y
[[1, 2, 99], [4, 5]]
>>> y[0] is x[0]
True  #see both point to the same object

そのような場合、copyモジュールのdeepcopy()function を使用する必要があります。オブジェクトの浅くないコピーを作成します。

于 2012-06-23T19:19:27.187 に答える
1

y = x何もコピーしません。yですでに参照されている同じオブジェクトに名前をバインドしxます。裸の名前に割り当てると、Pythonで何もコピーされません。

オブジェクトをコピーする場合は、コピーしようとしているオブジェクトで使用可能なメソッドを使用して、オブジェクトを明示的にコピーする必要があります。オブジェクトの種類はわからないxので、どのようにコピーできるかを言う方法はありませんが、copyモジュールには多くの種類で機能する関数がいくつか用意されています。この回答も参照してください。

于 2012-06-23T19:15:08.987 に答える