这一章节我们来讨论一下列表解析与矩阵
1.矩阵
矩阵(Matrix)是指纵横排列的二维数据表格
我们先从idle里面顶一个两个矩阵
>>> M=[ [1,2,3], [2,3,4], [3,4,5] ] >>> N=[ [5,6,7], [-2,-3,-4], [13,14,15] ] >>>
从上面来看,列表嵌套列表暂时成为一个矩阵,根据列表的特性,我们总是可以根据索引来操作矩阵
>>> M=[ [1,2,3], [2,3,4], [3,4,5] ] >>> N=[ [5,6,7], [-2,-3,-4], [13,14,15] ] >>> M[1] [2, 3, 4] >>> N[0][0] 5 >>>
2.列表解析与矩阵
由于列表解析是迭代所有的行与列,因此,对于矩阵这种数据格式的操作尤为好用
下面是遍历每一行
>>> [row for row in M] [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
遍历某一列
>>> [M[row][1] for row in range(3)] [2, 3, 4]
遍历对角线
>>> [M[i][i] for i in range(3)] [1, 3, 5] >>>
遍历每一个元素
>>> [M[row][col] for row in range(3) for col in range(3)] [1, 2, 3, 2, 3, 4, 3, 4, 5] >>>
列举M+N之后的元素
>>> M=[ [1,2,3], [2,3,4], [3,4,5] ] >>> N=[ [5,6,7], [-2,-3,-4], [13,14,15] ] >>> [M[row][col]+N[row][col] for row in range(3) for col in range(3)] [6, 8, 10, 0, 0, 0, 16, 18, 20] >>>
M+N之后组成新矩阵
>>> M=[ [1,2,3], [2,3,4], [3,4,5] ] >>> N=[ [5,6,7], [-2,-3,-4], [13,14,15] ] >>> [[M[row][col]+N[row][col] for col in range(3)] for row in range(3)] [[6, 8, 10], [0, 0, 0], [16, 18, 20]] >>>
M*N之后组成新矩阵
>>> M=[ [1,2,3], [2,3,4], [3,4,5] ] >>> N=[ [5,6,7], [-2,-3,-4], [13,14,15] ] >>> [[M[row][col]*N[col][row] for col in range(3)] for row in range(3)] [[5, -4, 39], [12, -9, 56], [21, -16, 75]] >>>
总结:这一章节主要讲述了通过列表的特性操作矩阵,以及列表解析与矩阵结合的矩阵运算
这一章节就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录