Home  >  Article  >  Backend Development  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 23:37:30266browse

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

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 the toList() method, follow these steps:

<code class="python">import numpy as np

# 創建一個 NumPy 陣列
arr = np.array([[1, 2, 3], [4, 5, 6]])

# 使用 tolist() 方法將陣列轉換為列表
list_from_array = arr.tolist()

# 列印轉換後的列表
print(list_from_array)</code>

Output:

[[1, 2, 3], [4, 5, 6]]

Please note that the toList() method will remove the elements from NumPy data types (such as np.int32 or np.float32) are converted 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.

The above is the detailed content of 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?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn