我刚接触Python,正在研究矩阵转置,但发现代码很冗长,请问有没有简单的方法?
mymatrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]
for myrow in mymatrix:
print(myrow)
print("\n")
t_matrix = zip(*mymatrix)
for myrow in t_matrix:
print(myrow)
要导入numpy,您需要先安装它。当应用于一维矩阵时,Numpy的转置返回类似的结果。
import numpy
mymatrix=[[1,2,3],[4,5,6]]
print(mymatrix)
print("\n")
print(numpy.transpose(mymatrix))
import numpy as np
matrix = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]] )
print(matrix.T)
不使用numpy
修改:适用于Python2和Python3
Python3
[*zip(*matrix)]
Python2
zip(*matrix)
zip
函数:mymatrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]
myTransposedMatrix = list(zip(*mymatrix))
>>> myTransposedMatrix
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
python2
。 - Netwave