Python:二维列表下标互换方式(矩阵转置)
我就废话不多说了,直接上代码吧!
#!/usr/bin/env python # coding:UTF-8 """ @version: python3.x @author:曹新健 @contact: [email protected] @software: PyCharm @file: 二维列表下标互换(矩阵转置).py @time: 2018/12/30 10:24 """ ''' 矩阵转置 将[[1,2,3],[4,5,6],[7,8,9]] 转换为[[1,4,7],[2,5,8],[3,6,9]] ''' ''' #方法一:默认列表值均初始为0,防止换为位置时,坐标越界 list1 = [[1,2,3],[4,5,6],[7,8,9]] list2 = [[0,0,0],[0,0,0],[0,0,0]] for i in range(3): for j in range(3): list2[j][i] = list1[i][j] print(list2) ''' ''' #方法二:互换位置,空列表插入值 list1 = [[1,2,3],[4,5,6],[7,8,9]] list2 = [[],[],[]] for i in range(3): for j in range(3): list2[j].insert(i,list1[i][j]) print(list2) ''' ''' #方法三:行列互换 list1 = [[1,2,3],[4,5,6],[7,8,9]] print([[list1[j][i] for i in range(3)] for j in range(3)]) ''' #方法四:取每行的第i列,即列转换为行 list1 = [[1,2,3],[4,5,6],[7,8,9]] print([[row[i] for row in list1] for i in range(3)])
相关推荐
doubinning 2019-12-02
jzlixiao 2020-07-29
Leonwey 2020-06-01
singer 2019-12-13
lmseohy 2015-06-17
ciqingloveless 2019-03-21
olyqcool 2015-06-17
EdwardWong 2006-11-07
GuangkuoDing 2012-02-06
anningzhu 2017-07-18
liushuibufuqin 2017-12-12
allentony 2018-06-19
xinhao 2018-05-15
Amonos 2018-04-13
chouliqingke 2018-04-03
Fourierrr 2018-02-08