📅  最后修改于: 2023-12-03 15:06:20.287000             🧑  作者: Mango
在Python中,二维数组是一种存储多个相同类型数据的数据结构,其中每个元素由两个下标表示,即行和列。本文将介绍二维数组的基本操作、创建方式和常见使用场景。
Python中可以通过以下方式创建二维数组:
matrix = [[i*j for j in range(4)] for i in range(4)]
print(matrix)
# [[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9]]
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
print(matrix)
# [[1 2]
# [3 4]]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0][0]) # 1
print(matrix[2][2]) # 9
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[0][0] = 0
print(matrix)
# [[0, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[1] = [0, 0, 0]
print(matrix)
# [[0, 2, 3], [0, 0, 0], [7, 8, 9]]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=' ')
print()
# 1 2 3
# 4 5 6
# 7 8 9