How to define and assign values to a two-dimensional array in Python?
In Python, you can define a two-dimensional array using nested lists and assign values to it. Here is an example:
# 定义一个3x3的二维数组
array_2d = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# 对二维数组进行赋值
array_2d[0][0] = 1
array_2d[1][1] = 2
array_2d[2][2] = 3
# 打印二维数组
for row in array_2d:
print(row)
Output result:
[1, 0, 0]
[0, 2, 0]
[0, 0, 3]
In the example above, we defined a 3×3 two-dimensional array, array_2d, and initialized it to all zeros. We then assigned values to each element of the two-dimensional array using array_2d[i][j]. Finally, we printed the contents of the two-dimensional array row by row using nested loops.