numpy实现
import numpy as np np.transpose([list]) # 矩阵转置 np.transpose([list]).tolist() # 矩阵转list
>>> import numpy as np
>>> np.transpose([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
>>> np.transpose([[1, 2, 3], [1, 2, 3], [1, 2, 3]]).tolist()
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
矩阵的转置就是从行变成列, 列变成行
用zip将一系列可迭代对象中的元素打包为元组,之后将这些元组放置在列表中,两步加起来等价于行列转置。
# 矩阵的转置
def transpose(list1):
return [list(row) for row in zip(*list1)]
list1 = [[1, 4], [2, 5], [3, 6]]
print(transpose(list1)) # [[1, 2, 3], [4, 5, 6]]
# 矩阵逆转
def invert(list1):
return [row[::-1] for row in list1]
list1 = [[1, 4], [2, 5], [3, 6]]
print(invert(list1)) # [[4, 1], [5, 2], [6, 3]]
取出每行的元素,逆序索引遍历 = 左右翻转。