python二维列表(矩阵转置)
1. 方法一
lst1=[ [2,0,0,2], [2,1,2,1], [3,1,1,2], [0,1,0,1], ] lst1[:]=[list(reversed(item)) for item in lst1] print(lst1)
2. 方法二
lst2=[ [2,0,0,2], [2,1,2,1], [3,1,1,2], [0,1,0,1], ] lst2[:]=[list(item) for item in zip(*lst2)] print(lst2)
3. 方法三
import numpy as np # 定义一个矩阵 matrix = np.array([ [2,0,0,2], [2,1,2,1], [3,1,1,2], [0,1,0,1], ]) # 对矩阵进行转置 transpose_matrix = np.transpose(matrix) matrix[:]=transpose_matrix.tolist() print(matrix)
4. 方法四
lst3=[ [2,0,0,2], [2,1,2,1], [3,1,1,2], [0,1,0,1], ] #针对行数与列数相等的矩阵,对角线上的元素与对角线下的互换,lst3[i][j]<--->lst3[j][i] for row in range(len(lst3)): for col in range(row+1,len(lst3)): print((row,col)) if row<=len(lst3)-1 and col<=len(lst3)-1: lst3[row][col],lst3[col][row]=lst3[col][row],lst3[row][col] [print(item,end="\n") for item in lst3]
小结:简单记录一下知识点,注意zip内置函数的用法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署