使用列表理解的矩阵运算-错误的结果

时间:2019-12-28 08:35:22

标签: python list-comprehension

我无法弄清楚我的代码中关于python列表理解的问题。这是我的代码

  File "manage.py", line 16
    ) from exc
         ^
SyntaxError: invalid syntax

输出为def matrix_operator(m, n, operations): matrix = [[0] * n] * m for item in operations: matrix = [[col + 1 for col in row if row.index(col) < item[1]] for row in matrix if matrix.index(row) < item[0]] return matrix m = matrix_operator(3, 3, [[2, 2], [3, 3]]) print(m)

但所需的输出是[[2, 2, 2], [2, 2, 2], [2, 2, 2]]

1 个答案:

答案 0 :(得分:-1)

如果使用乘法创建矩阵,则它们是同一矩阵的副本:

>>> a = [[0]*4]*2
>>> a[0][1] = 2
>>> a
[[0, 2, 0, 0], [0, 2, 0, 0]]