2017-02-24 54 views
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]] 

誰能解釋什麼是這種行爲背後?

+0

'result = [[0] *(width-2)] *(height-2)'請注意所有內部列表都是一樣的。 – PeterE

+0

爲什麼我在初始化「結果」後不修復它們? –

+0

這些是*列表*不是數組。 –

回答

0

數組'multiplication'正在複製引用到正在乘的東西,即生成的數組的每個元素都指向相同的實際實例。因此,修改一個修改所有的元素。

+0

謝謝! '複製參考'是現場。 –