Ray*_*ger 5

矩阵是二维结构.在普通的Python中,矩阵最自然的表示形式是列表.

因此,您可以将行矩阵写为:

[[1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

并将列矩阵写为:

[[1],
 [2],
 [3],
 [4]]
Run Code Online (Sandbox Code Playgroud)

这也很好地扩展到mxn矩阵:

[[10, 20],
 [30, 40],
 [50, 60]]
Run Code Online (Sandbox Code Playgroud)

有关如何在纯Python中开发完整矩阵包的示例,请参阅matfunc.py.它的文档在这里.

这里有一个使用list-of-lists表示在普通python中进行矩阵乘法的例子:

>>> from pprint import pprint
>>> def mmul(A, B):
        nr_a, nc_a = len(A), len(A[0])
        nr_b, nc_b = len(B), len(B[0])
        if nc_a != nr_b:
            raise ValueError('Mismatched rows and columns')
        return [[sum(A[i][k] * B[k][j] for k in range(nc_a))
                 for j in range(nc_b)] for i in range(nr_a)]

>>> A = [[1, 2, 3, 4]]
>>> B = [[1],
         [2],
         [3],
         [4]]

>>> pprint(mmul(A, B))
[[30]]

>>> pprint(mmul(B, A), width=20)
[[1, 2, 3, 4],
 [2, 4, 6, 8],
 [3, 6, 9, 12],
 [4, 8, 12, 16]]
Run Code Online (Sandbox Code Playgroud)

正如另一位受访者所提到的,如果你认真对待矩阵工作​​,你应该安装numpy,它直接支持许多矩阵操作:

  • 永远不要太早开始.老实说,我认为使用numpy数组比尝试使用列表复制功能要容易得多. (3认同)