2017-03-15 52 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]]) 
相关问题