0
我写了这段代码对给定的图像进行平均滤波。其中,我首先初始化一个二维数组。但是,当我尝试将值分配给特定的单元格时,它实际上将值分配给了整个列。请看下图:python多维数组乘法行为
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]])
输出是这样的:
[[5, 0], [5, 0]]
[[5, 4], [5, 4]]
[[4, 4], [4, 4]]
[[4, 4], [4, 4]]
谁能解释什么是这种行为背后?
'result = [[0] *(width-2)] *(height-2)'请注意所有内部列表都是一样的。 – PeterE
为什么我在初始化“结果”后不修复它们? –
这些是*列表*不是数组。 –