有人能帮我找出代码中的错误吗?如果我创建一个具有静态初始值的空白二维矩阵,它会返回正确的转置矩阵。而如果我使用 for l 创建一个空白矩阵...
有人能帮我找出代码中的错误吗?如果我创建一个具有静态初始值的空白二维矩阵,它会返回正确的转置矩阵。而如果我使用 for 循环创建一个空白矩阵,它会返回答案中所有行的最后一行。
# Original Matrix :
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Expected Transpose :
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
# Actual Transpose :
[[3, 6, 9],
[3, 6, 9],
[3, 6, 9]]
# Transpose Matrix
def transpose_mtx(original):
t_cols = len(original)
t_rows = len(original[0])
# creating a blank matrix with 0s of transpose shape
row = [0 for _ in range(t_cols)]
t_mtx = [row for _ in range(t_rows)]
# t_mtx = [[0,0,0],[0,0,0], [0,0,0]]
# if I keep this line instead, it returns correct answer
# rows of original
for i in range(len(original)):
# columns of original
for j in range(len(original[0])):
# interchange items
t_mtx[j][i] = original[i][j]
return t_mtx
my_mtx = [[1,2, 3],
[4, 5, 6],
[7, 8, 9]]
print(transpose_mtx(my_mtx))