[英]python multi-dimensional array multiplication behavior
I wrote this code to do an mean filtering to a given image. 我编写此代码是为了对给定图像进行均值过滤。 In it, I first initialize a 2-d array.
在其中,我首先初始化一个二维数组。 But when I try to assign a value to a specific cell it actually assigned the value to the whole column.
但是,当我尝试为一个特定的单元格分配一个值时,它实际上将该值分配给了整个列。 See below:
见下文:
def boxBlur(image):
height = len(image)
width = len(image[0])
result = [[0]*(width-2)]*(height-2)
for i in range(height-2):
for j in range(width-2):
mysum = image[i][j] + image[i][j+1] + image[i][j+2] + image[i+1][j] + image[i+1][j+1] + image[i+1][j+2] + image[i+2][j] + image[i+2][j+1] + image[i+2][j+2]
result[i][j] = mysum / 9
print result
boxBlur([[7,4,0,1],
[5,6,2,2],
[6,10,7,8],
[1,4,2,0]])
The output is like: 输出如下:
[[5, 0], [5, 0]]
[[5, 4], [5, 4]]
[[4, 4], [4, 4]]
[[4, 4], [4, 4]]
Can anyone explain exactly what's behind this behavior? 谁能确切解释此行为的背后原因?
The array 'multiplication' is copying a reference to the thing you are multiplying ie each element of the generated array points to the same actual instance. 数组“乘法”正在复制对您要乘法的对象的引用,即所生成数组的每个元素都指向相同的实际实例。 Hence, modifying one modifies all the elements.
因此,修改一个会修改所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.