How can Python convert a two-dimensional list into an array?

In Python, you can use the numpy library to convert a two-dimensional list into an array. Here is an example code:

import numpy as np

# 二维列表
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# 将二维列表转换为数组
array = np.array(list_2d)

print(array)

Output result:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

In the code above, we start by importing the numpy library. Next, we define a two-dimensional list called list_2d. We convert the two-dimensional list to an array using the np.array() function and save the result in the array variable. Lastly, we print the array.

Please make sure that you have installed the numpy library before running the code, you can use the following command to install it:

pip install numpy
广告
Closing in 10 seconds
bannerAds