现在有个二维数组:data=[0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3],每一行都是[0,1,2,3],要求顺时针旋转90度,变成每一列都是[0,1,2,3]。
#首先生成一维数组的语句是: row=[i for i in range(6)] print(row) #运行结果: #[0, 1, 2, 3, 4, 5] #生成二维数组的语句是: data=[[i for i in range(4)] for k in range(4)] for j in data: print(j) ''' 相当于是把一维数组的整体作为上面的i 运行结果是: [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] '''
数组扩充行和列:
def trans(m): a = [[] for i in m[0]] for i in m: for j in range(len(i)): a[j].append(i[j]) return a m = [[1, 2], [3, 4], [5, 6]] # 想像第一个列表是原始的,后面的是往里添加的 print(trans(m)) # result:[[1, 3, 5], [ 2, 4, 6]] #来自于https://www.cnblogs.com/anpengapple/p/5427367.html
矩阵转置(含过程):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] def trans(m): for i in range(len(m)): for j in range(i): m[i][j], m[j][i] = m[j][i], m[i][j] print(m) trans(m) ''' 运行结果: [[1, 4, 3], [2, 5, 6], [7, 8, 9]] [[1, 4, 7], [2, 5, 6], [3, 8, 9]] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] '''
矩阵转置(不含中间过程):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] def trans(m): for i in range(len(m)): for j in range(i): m[i][j], m[j][i] = m[j][i], m[i][j] return m print(trans(m)) #注意:只适合方阵
矩阵的运算参考:https://www.cnblogs.com/chamie/p/4870078.html