在Python中创建矩阵的Python程序
Python中没有特定的数据类型来创建矩阵,我们可以使用list列表来创建矩阵。
考虑下面的示例,
mat = [ [10, 20, 30], [40, 50, 60], [70, 80, 80] ]
可以认为是3x3矩阵,“mat”矩阵中有3行3列。
访问矩阵元素
就像C/C++中的矩阵一样,我们也可以访问Python中的元素。
考虑下面的程序,
#Python矩阵创建
mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 80]
]
#打印矩阵
print("mat: ", mat)
#打印行
print("mat[0]: ", mat[0])
print("mat[1]: ", mat[1])
print("mat[2]: ", mat[2])
#打印特定元素
print("mat[0][0]: ", mat[0][0])
print("mat[0][1]: ", mat[0][1])
print("mat[0][2]: ", mat[0][2])
print("mat[1][0]: ", mat[1][0])
print("mat[1][1]: ", mat[1][1])
print("mat[1][2]: ", mat[1][2])
print("mat[2][0]: ", mat[2][0])
print("mat[2][1]: ", mat[2][1])
print("mat[2][2]: ", mat[2][2])
#使用循环打印矩阵(矩阵形式)
print("Matrix is: ")
for i in range(3):
for j in range(3):
print(mat[i][j], end = " ") print() #打印新行输出结果
mat: [[10, 20, 30], [40, 50, 60], [70, 80, 80]] mat[0]: [10, 20, 30] mat[1]: [40, 50, 60] mat[2]: [70, 80, 80] mat[0][0]: 10 mat[0][1]: 20 mat[0][2]: 30 mat[1][0]: 40 mat[1][1]: 50 mat[1][2]: 60 mat[2][0]: 70 mat[2][1]: 80 mat[2][2]: 80 Matrix is: 10 20 30 40 50 60 70 80 80