Converting a NumPy Array to a Python List
NumPy arrays provide efficient data structures for numerical computations. However, sometimes it is necessary to convert them to Python list for further data processing.
Solution: toList()
NumPy provides a toList() method to convert an array to a Python list. This method converts the elements in the array to the nearest Python type (e.g., int, float).
To use toList() method, follow these steps:
import numpy as np
# 創建一個 NumPy 陣列
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 使用 tolist() 方法將陣列轉換為列表
list_from_array = arr.tolist()
# 列印轉換後的列表
print(list_from_array)
Output:
[[1, 2, 3], [4, 5, 6]]
Please note that the toList() method will Elements are converted from NumPy's data types (such as np.int32 or np.float32) to Python data types (such as int or float). If you wish to preserve NumPy's data types, you can use the list() method on an array, which will produce a list of NumPy scalars.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3