给定矩阵
matrix = [[2, None],
[2, None]]
我需要计算这个的转置。我做了以下事情:
def transpose(matrix):
# Makes a copy of the matrix
result = matrix
# Computes tranpose
for i in range(2):
for j in range(2):
result[j][i] = matrix[i][j]
return result
但这给了我错误的结果:
[[2, None],
[None, None]]
虽然它应该是
[[2, 2],
[None, None]]
有人可以告诉我我的代码出错吗?
答案 0 :(得分:3)
问题是变量matrix
引用matrix
,也就是说,你没有复制,所以在for循环中你实际上也改变了matrix
。您可以通过使用list
复制result = [list(x) for x in matrix]
结果来解决此问题:
import numpy as np
matrix = np.matrix([[2, None],[2, None]])
请参阅问题:the other
请注意,更简单的方法是使用How to clone or copy a list?:
matrix.T
然后使用matrix([[2, 2],
[None, None]], dtype=object)
来获得转置:
expect
答案 1 :(得分:3)
您引用相同的矩阵,尝试初始化一个新矩阵:
def transpose(matrix):
# Makes a copy of the matrix
result = [[None]* len(x) for x in matrix]
# Computes tranpose
for i in range(2):
for j in range(2):
result[i][j] = matrix[j][i]
return result
您也可以使用list comprehesion
为通用矩阵执行此操作def transpose(matrix):
return [[matrix[i][j] for i in range(len(matrix[j]))] for j in range(len(matrix))]
答案 2 :(得分:1)
# We can use the below method also:
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
mat_trans = []
trans = []
trans1 = []
trans2 = []
trans3 = []
for row in matrix:
for i in range(4):
if i == 0:
trans.append(row[i])
if i == 1:
trans1.append(row[i])
if i == 2:
trans2.append(row[i])
if i == 3:
trans3.append(row[i])
mat_trans.append(trans)
mat_trans.append(trans1)
mat_trans.append(trans2)
mat_trans.append(trans3)
trans = []
print(mat_trans)
答案 3 :(得分:0)
假设矩阵是矩形的(即所有一维数组中的列表大小相同),可以简单地将转置写为如下。
def transpose(matrix):
num_rows = len(matrix)
num_cols = len(matrix[0])
result = []
for j in range(num_cols):
rowresult = []
for i in range(num_rows):
rowresult.append(matrix[i][j])
result.append(rowresult)
return result
注意:这不是最有效的实施方式。