Python 矩阵旋转意外结果

Python 矩阵旋转意外结果,python,matrix,Python,Matrix,我是Python的新手,遇到了一个关于矩阵旋转的问题。 下面是我的代码 def rotateMatrix(matrix): if matrix == []: return [] row, col = len(matrix), len(matrix[0]) res = [[0]*row]*col for i in range(row): for j in range(col): res[col-1-j][i]

我是Python的新手,遇到了一个关于矩阵旋转的问题。 下面是我的代码

def rotateMatrix(matrix):
    if matrix == []:
        return []
    row, col = len(matrix), len(matrix[0])
    res = [[0]*row]*col
    for i in range(row):
        for j in range(col):
            res[col-1-j][i] = matrix[i][j]
    return res

mat = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
print rotateMatrix(mat)
所有4行的打印结果都是[4,8,12]!!!我只是不知道这个问题出在哪里

res = [[0]*row]*col
因为您在重复一个列表
col
次,所以会出现这种行为

>>> res = [[0]*3]*4
>>> res
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> res[0][0] = 1
>>> res
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
和这个一样

>>> x = []
>>> y = x
>>> x.append(5)
>>> x
[5]
>>> y
[5]
相反,如果你想要一行,你应该使用列表理解

res = [ [ 0 for r in range(rows) ] for c in range(col) ]


@比我快一分钟;-)谢谢!我只是看到了用[[0]*r]*c生成零矩阵的地方,但没有意识到这里的问题
res = [ [ 0 ] * rows for c in range(col) ]