How to create and assign values to a two-dimensional array in Python?

In Python, you can use list comprehension to build and assign values to a 2D array.

For example, to create a 3×3 two-dimensional array and assign it with values of 0, you can use the following code:

# 创建一个3x3的二维数组,并赋值为0
matrix = [[0 for _ in range(3)] for _ in range(3)]

# 输出二维数组
for row in matrix:
    print(row)

One way to create a 3×3 two-dimensional array with values from 1 to 9 is by using the following code:

# 创建一个3x3的二维数组,并赋初值为1到9
counter = 1
matrix = [[counter + col + 3*row for col in range(3)] for row in range(3)]

# 输出二维数组
for row in matrix:
    print(row)

Using this method, it is easy to construct a two-dimensional array and assign values to it.

bannerAds