import numpy as npA = np.mat([[1,2,3],[4,5,6],[7,8,9]])print(A.T)print(A.swapaxes(0, 1))# 均輸出# [[1 4 7]# [2 5 8]# [3 6 9]]
import numpy as npA = [[1,2,3],[4,5,6],[7,8,9]]print(np.transpose(A))# 輸出# [[1 4 7]# [2 5 8]# [3 6 9]]
*
號(hào)操作符,可以將元組解壓為列表。zip(A)
相當(dāng)于打包,打包為元組的列表:
>>> a = [1,2,3]>>> b = [4,5,6]>>> c = [4,5,6,7,8]>>> A = zip(a,b) # 打包為元組的列表[(1, 4), (2, 5), (3, 6)]>>> zip(a,c) # 元素個(gè)數(shù)與最短的列表一致[(1, 4), (2, 5), (3, 6)]>>> zip(*A) # 與 zip 相反,*A 可理解為解壓,返回二維矩陣式[(1, 2, 3), (4, 5, 6)]
A = [[1,2,3],[4,5,6],[7,8,9]]print(*A) #[1, 2, 3] [4, 5, 6] [7, 8, 9]#zip()返回的是一個(gè)對(duì)象。如需展示列表,需手動(dòng) list() 轉(zhuǎn)換。#print(zip(*A)) #<zip object at 0x000001CD7733A2C8>print(list(zip(*A)))# 輸出# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
這里python中星號(hào)(*)的作用是將變量中可迭代對(duì)象的元素拆解出來。
A = [[1,2,3],[4,5,6],[7,8,9]]#print(len(A)) #矩陣行數(shù)#print(len(A[0])) #矩陣列數(shù)B = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]print(B)# 輸出# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
B = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
這句寫的清楚一點(diǎn)就是:
A = [[1,2,3],[4,5,6],[7,8,9]]#print(len(A)) #矩陣行數(shù)#print(len(A[0])) #矩陣列數(shù)for i in range(len(A[0])):#len(A[0])矩陣列數(shù) for j in range(len(A)):#len(A)矩陣行數(shù) #轉(zhuǎn)置就是A[i][j]和A[j][i]互換 A[j][i], A[i][j] = A[i][j], A[j][i]print(A)# 輸出# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
因?yàn)檗D(zhuǎn)置矩陣的對(duì)稱性,可以更省時(shí)間的寫成:
A = [[1,2,3],[4,5,6],[7,8,9]]#print(len(A)) #矩陣行數(shù)#print(len(A[0])) #矩陣列數(shù)for i in range(len(A[0])):#len(A[0])矩陣列數(shù) for j in range(i,len(A)):#len(A)矩陣行數(shù) #轉(zhuǎn)置就是A[i][j]和A[j][i]互換 A[j][i], A[i][j] = A[i][j], A[j][i]print(A)# 輸出# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
A = [[1,2,3],[4,5,6],[7,8,9]]B=[]for i in range(len(A[0])):#len(A[0])矩陣列數(shù) temp = [] for j in range(len(A)):#len(A)矩陣行數(shù) temp.append(A[j][i]) B.append(temp)print(B)# 輸出# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
聯(lián)系客服