又有一题不是特别会做,求教大家, 需要用 python 写一个 function 去得出某个二维矩阵的转置矩阵。 好像看起来挺简单,转置矩阵就是 Nij=Nji,但是还没想到思路。因此求教大神。
如题,
Exercise 4. Within the module matrix_utils.py write a function transpose() . The function should accept one parameter matrix which is a two-dimensional matrix (in Python it is a list of lists of the same size). The function should return a transposed matrix. Example usages of this functions: matrix1 = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4] ] print("Transposed:", transpose(matrix1)) Transposed: [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]] matrix2 = [[ ' a ' , ' b ' ], [ ' c ' , ' d ' ] ] print("Transposed:", transpose(matrix2)) Transposed: [[ 'a ' , ' c '] , [ 'b ' , ' d ']]
1
KylinJiang 2019-11-08 16:46:56 +08:00
emmm 不太在意性能的话:
|
2
KylinJiang 2019-11-08 16:47:12 +08:00
map(list,zip(*N))
N 为你的多维数组 |
3
HHH01 OP @KylinJiang 不能用 zip,还没学到,用 lists 的 loop。。。
|
4
HHH01 OP 我想到的思路,但是有问题
def transpose(matrix): matrix == list n = len(matrix) tran_m = [] m=0 for m in range(0,n): m += len(matrix[m]) temp=[] for i in range(n): tran_m=tran_m+[temp] for j in range(m): temp=temp+[matrix[j][i]] return tran_m |
5
HHH01 OP 想到了!
def transpose(matrix): matrix == list tran_m = [] for i in range(len(matrix[0])): temp=[] for j in range(len(matrix)): temp=temp+[matrix[j][i]] tran_m=tran_m+[temp] return tran_m |
6
cherbim 2019-11-08 17:09:49 +08:00 1
```
def transpose(m): result = [] row = len(m) col = len(m[0]) for i in range(col): item = [] for index in range(row): item.append(m[index][i]) result.append(item) return result matrix1 = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] print("Transposed:", transpose(matrix1)) ``` |
7
cherbim 2019-11-08 17:11:14 +08:00
获得行数和列数,然后调一下行和列存入另一个矩阵
|
8
TimePPT 2019-11-08 17:37:31 +08:00
进来学习。
以及,每次看到这种题就感慨 numpy 真香 😂 |
10
009694 2019-11-08 17:47:02 +08:00
t = [[1,2,3],[4,5,6]]
t_t = [[row[i] for row in t] for i in range(max(len(t) for t in t))] |
11
009694 2019-11-08 17:49:03 +08:00
transpose = lambda t:[[row[i] for row in t] for i in range(max(len(t) for t in t))]
|
13
ddzzhen 2019-11-08 18:15:10 +08:00 via Android
pandas 直接 T 就行了
|
14
xiri 2019-11-08 18:24:39 +08:00
emmmm,如果不是作业的话 numpy 分分钟就 over 了
|
15
coordinate 2019-11-08 19:03:37 +08:00
for i in range(len(mat)):
for j in range(i+1, len(mat[0])): mat[i][j], mat[j][i] = mat[j][i], mat[i][j] |
16
necomancer 2019-11-08 20:59:31 +08:00
traspose = lambda x : [ [x[i][j] for i in range(len(x))] for j in range(len(x[0]))]
转置只能对 (mxn) 形状的列表有效。 |
18
HHH01 OP 还是众人拾柴火焰高
|
19
cshlxm 2019-11-09 14:03:25 +08:00
import numpy 哈哈哈
list 的话,只能读一行,再循环每一行 append 一个对应数 |
20
yuuiasuka 2019-11-11 16:58:11 +08:00
可以参考下 numpy 里面的 transpose 方法是怎么实现的。
|