【基础入门题】2022.01.07
转置一个m行n列的矩阵,即把矩阵每一个元素的行列标号互换。
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
方法一:双重循环交接行列
m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split()) Array = [[0 for i in range(m)] for j in range(n)] #初始结果矩阵为0矩阵 t = [[i+1+j*n for i in range(n)] for j in range(m)] #转置前的矩阵 for i in range(n): for j in range(m): Array[i][j]=t[j][i] #交换行列标号 print('转置前:') for a in t: for b in a: print(str(b).rjust(3), end='') print() print('转置后:') for a in Array: for b in a: print(str(b).rjust(3), end='') print()
输出结果:
请输入矩阵的行和列(用空格隔开):4 6
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
1 7 13 19
2 8 14 20
3 9 15 21
4 10 16 22
5 11 17 23
6 12 18 24
方法二:行列式
m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split()) t = [[i+1+j*n for i in range(n)] for j in range(m)] #转置前的矩阵 Array = [[t[i][j] for i in range(len(t))] for j in range(len(t[0]))] #推导式一行搞定 print('转置前:') for a in t: for b in a: print(str(b).rjust(3), end='') print() print('转置后:') for a in Array: for b in a: print(str(b).rjust(3), end='') print()
方法三:内置函数zip()
m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split()) t = [[i+1+j*n for i in range(n)] for j in range(m)] #转置前的矩阵 Array = [list(_) for _ in zip(*t)] #zip()超级简单 print('转置前:') for a in t: for b in a: print(str(b).rjust(3), end='') print() print('转置后:') for a in Array: for b in a: print(str(b).rjust(3), end='') print()
方法四:numpy库函数
import numpy as np m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split()) t = np.arange(1,m*n+1) #或:t = np.array([*range(1,m*n+1)]) t = t.reshape(m,n) #一维数组reshape成二维数组 Array = t.T #一个.T就能转置,或者使用:Array = np.transpose(t) print('转置前:') print(t) t = [list(_) for _ in t] #转内置列表格式 print('转置前标准格式:') for a in t: for b in a: print(str(b).rjust(3), end='') print() print('转置后:') print(Array) Array = [list(_) for _ in Array] print('转置后标准格式:') for a in Array: for b in a: print(str(b).rjust(3), end='') print()