python創建矩陣
There is no specific data type in Python to create a matrix, we can use list of list to create a matrix.
Python中沒有特定的數據類型來創建矩陣,我們可以使用list列表來創建矩陣 。
Consider the below example,
考慮下面的示例,
mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 80]
]
It can be considered a 3x3 matrix, there are 3 rows and 3 columns in 'mat' matrix.
可以認為是3x3矩陣,“ mat”矩陣中有3行3列。
訪問矩陣元素 (Accessing matrix elements)
Just like matrix in C/C++, we can access the elements in Python also.
就像C / C ++中的矩陣一樣,我們也可以訪問Python中的元素。
Consider the below program,
考慮下面的程序,
# Python matrix creation
mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 80]
]
# printing the matrix
print("mat: ", mat)
# printing rows
print("mat[0]: ", mat[0])
print("mat[1]: ", mat[1])
print("mat[2]: ", mat[2])
# printing specific elements
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])
# printing matrix using loop (matrix form)
print("Matrix is: ")
for i in range(3):
for j in range(3):
print(mat[i][j], end = " ")
print() # prints new line
Output
輸出量
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
翻譯自: https://www.includehelp.com/python/program-to-create-matrix.aspx
python創建矩陣