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
爲什麼我在初始化「結果」後不修復它們? –
這些是*列表*不是數組。 –