"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The following is a question-and-answer English title that fits the content of the article: How do I convert a NumPy array to a Python list?

The following is a question-and-answer English title that fits the content of the article: How do I convert a NumPy array to a Python list?

Published on 2024-11-16
Browse:135

以下是一個符合文章內容的問答式英文標題:

How do I convert a NumPy array to a Python list?

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.

Latest tutorial More>

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