Define calculated matrix transpose function
1) use cycle transpose
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
# 打印矩阵
def printMatrix(m):
for ele in m:
for e in ele:
print('%3d' % e, end='')
print('')
# 转置矩阵
def transformMatrix(m):
rt = [[] for i in m[0]] # m[0] 有几个元素,说明原矩阵有多少列。此处创建转置矩阵的行
for ele in m:
for i in range(len(ele)):
# rt[i] 代表新矩阵的第 i 行
# ele[i] 代表原矩阵当前行的第 i 列
rt[i].append(ele[i])
return rt
printmatrix(matrix)
print('-'*40)
printmatrix(transformMatrix(matrix))
1 2 3 4
5 6 7 8
9 10 11 12
----------------------------------------
1 5 9
2 6 10
3 7 11
4 8 12
2) using the zip () function transpose
Description : the plurality of functions into a ZIP sequence: a first element of the plurality of sequences are combined into the first element, the second element of the plurality of sequences are combined into the second sequence ...
Analysis : the original matrix to do the reverse parameters collection
def transformMatrix(m):
# 逆向参数收集,将矩阵中多个列表转换成多个参数,传给 zip
return list(zip(*m))
printmatrix(matrix)
print('-'*40)
printmatrix(transformMatrix(matrix))
1 2 3 4
5 6 7 8
9 10 11 12
----------------------------------------
1 5 9
2 6 10
3 7 11
4 8 12
3) using transposition module numpy
Description:
- numpy module provides TRANSPOSE () function performs transposition, the return value of the function is a built-in type numpy: array
- Calling array of tolist () method to convert array to list list
import numpy
def transformMatrix(m):
return numpy.transpose(m).tolist()
printmatrix(matrix)
print('-'*40)
printmatrix(transformMatrix(matrix))
1 2 3 4
5 6 7 8
9 10 11 12
----------------------------------------
1 5 9
2 6 10
3 7 11
4 8 12