数组值未分配给变量值

时间:2019-05-15 01:44:43

标签: python python-3.x for-loop

我很困惑,因为在for循环中我正在打印一个数组值。但是,退出循环后,输出与我正在打印的内容不匹配。发生了什么事?

代码:

import numpy as np
from itertools import product

def boxBlur(image):

        m = len( image ) - 1
        n = len( image[1] ) - 1

        out = [ [0]* ( n - 1 ) ] * ( m - 1 )

        for i,j in product( range(1,m) , range(1,n) ):
                vals = np.array(image[i-1:i+2]).transpose()[j-1:j+2].flatten()

                I = i - 1
                J = j - 1

                out[I][J] = int( sum(vals) / 9 )

                print( "M[" + str(I) + "," + str(J) + "] = " + str(out[I][J]) ) 

        print(out)
        return out

image = [[7,4,0,1], 
         [5,6,2,2], 
         [6,10,7,8], 
         [1,4,2,0]]

boxBlur(image)

    M[0,0] = 5
    M[0,1] = 4
    M[1,0] = 4
    M[1,1] = 4
    [[4, 4], [4, 4]]

1 个答案:

答案 0 :(得分:1)

这是因为out[0]out[1]是完全相同的实例,这是由于以下原因造成的:

out = [ [0]* ( n - 1 ) ] * ( m - 1 )

重复运算符*重复相同的实例,而不创建副本。

您可以通过列表理解来完成所需的操作:

out = [[0]* ( n - 1 ) for _ in range(m - 1)]