2017-03-15 14 views
0

我有一個數組(稱爲圖像),我想要循環並使用numpy.roll函數進行調整。我也想存儲我即將調整的行的副本。這裏是我的代碼:Python,兩個變量應該是不同的,但它們保持不變 - 是np.roll責備?

for i in range(1, 10): 
    delta = function(i)  ### it's not important what this function is, just that it yields an int 

    x0 = image[i]   ### creating a variable to store the row before I change it 

    print x0[:20]   ###only printing the first 20 elements, as it's a very large array 

    image[i] = np.roll(x0, -delta) 

    print image[i][:20]  ###image[i] has now been updated using np.roll function 

    if np.array_equal(image[i], x0) == True: 
     print 'something wrong' 

現在是奇怪的事情發生在:當我運行這段代碼,我可以看到,x0和圖像[I]有很大的不同(如每頭20元的打印到屏幕)。不過,我也在屏幕上打印出了「錯誤的東西」,這非常令人困惑,因爲這實現了x0和image [i]是相等的。這是一個問題,因爲我的腳本的其餘部分依賴於x0和image [i]不相等(除非delta = 0),但腳本始終將它們視爲它們。

幫助感謝!

回答

-1

你應該只改變如下,你的問題將得到解決

for i in range(1, 10): 
    delta = function(i)  

    x0 = list(image[i])  

    print x0[:20]  

    image[i] = np.roll(x0, -delta) 

    print image[i][:20] 

if np.array_equal(image[i], x0) == True: 
    print 'something wrong' 

可以假設X0 - >和圖像[I] - >乙 X0 =圖像[I]

enter image description here

+0

,因爲這個答案不包含任何解釋,並創建這可能幫助你 –

+0

Downvoting一個列表而不是一個數組。 – user2357112

+0

嘿,你不能像列表一樣將列表或數組列表複製到另一個變量中...因爲列表或數組列表被視爲對象,並且當您指定另一個變量時,它們只會成爲對原始對象的引用,並且當您使用引用和詢問其他引用的值,他們給出相同的值 –

3

我也想存儲行的副本我將要調整

如果你想要一個副本,x0 = image[i]是不是你想要的。這使得行的視圖,而不是副本。如果你想要一個副本,調用copy

x0 = image[i].copy() 
+0

「行觀點」是什麼意思? – 11thHeaven

+0

@ 11thHeaven:[它共享'圖像'的數據,而不是將數據複製到新的緩衝區中。](http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html) – user2357112

0

這說明了什麼是一小陣怎麼回事:

In [9]: x = np.arange(12).reshape(3,4) 
In [10]: x 
Out[10]: 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11]]) 
In [11]: x0=x[0] 
In [12]: x[0] = np.roll(x0, 1) 
In [13]: x 
Out[13]: 
array([[ 3, 0, 1, 2], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11]]) 
In [14]: x0 
Out[14]: array([3, 0, 1, 2]) 

這裏x0x[0]的另一個名稱。對x[0]的更改也見於x0x0In [12]更改,可以通過2張打印進行驗證。

做同樣的,但要x0副本

In [15]: x0=x[1].copy() 
In [16]: x[1] = np.roll(x0, 1) 
In [17]: x 
Out[17]: 
array([[ 3, 0, 1, 2], 
     [ 7, 4, 5, 6], 
     [ 8, 9, 10, 11]]) 
In [18]: x0 
Out[18]: array([4, 5, 6, 7]) 

無副本的情況是一樣的:

In [19]: x[2] = np.roll(x[2], 1) 
In [20]: x 
Out[20]: 
array([[ 3, 0, 1, 2], 
     [ 7, 4, 5, 6], 
     [11, 8, 9, 10]]) 
相關問題