如何在 python 中表示列矩阵和行矩阵?
A =[1,2,3,4]
和
1
2
3
4
最佳答案
矩阵是二维结构。在普通 Python 中,矩阵最自然的表示形式是列表的列表。
因此,您可以将行矩阵写为:
[[1, 2, 3, 4]]
并将列矩阵写为:
[[1],
[2],
[3],
[4]]
这也很好地扩展到 m x n 矩阵:
[[10, 20],
[30, 40],
[50, 60]]
参见 matfunc.py有关如何在纯 Python 中开发完整矩阵包的示例。 它的文档是 here .
这里是一个使用列表列表表示在纯 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]]
正如另一位受访者提到的,如果您认真对待矩阵工作,那么您应该安装 numpy它直接支持许多矩阵运算:
关于python - python中的列矩阵表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15675667/