杰瑞科技汇

Python numpy转list的方法有哪些?

Of course! Converting a NumPy array to a standard Python list is a very common task. The primary and most efficient way to do this is by using the .tolist() method.

Python numpy转list的方法有哪些?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the basics, different data types, and important considerations.

The Main Method: numpy.ndarray.tolist()

This is the most straightforward and idiomatic way to convert a NumPy array to a Python list. It works recursively, meaning it will convert multi-dimensional arrays into nested lists.

Basic 1-Dimensional Array

For a simple, one-dimensional array, .tolist() converts it directly to a flat Python list.

import numpy as np
# Create a 1D NumPy array
arr_1d = np.array([1, 2, 3, 4, 5])
# Convert to a Python list
list_1d = arr_1d.tolist()
print(f"NumPy Array: {arr_1d}")
print(f"Type: {type(arr_1d)}")
print(f"\nPython List: {list_1d}")
print(f"Type: {type(list_1d)}")

Output:

Python numpy转list的方法有哪些?-图2
(图片来源网络,侵删)
NumPy Array: [1 2 3 4 5]
Type: <class 'numpy.ndarray'>
Python List: [1, 2, 3, 4, 5]
Type: <class 'list'>

Multi-Dimensional Arrays

.tolist() shines here, as it automatically handles the nested structure of the array.

import numpy as np
# Create a 2D NumPy array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Convert to a Python list (which will be a list of lists)
list_2d = arr_2d.tolist()
print(f"NumPy Array:\n{arr_2d}\n")
print(f"Python List: {list_2d}")
print(f"Type of outer element: {type(list_2d[0])}")

Output:

NumPy Array:
[[1 2 3]
 [4 5 6]]
Python List: [[1, 2, 3], [4, 5, 6]]
Type of outer element: <class 'list'>

This works for any number of dimensions (3D, 4D, etc.).


Handling Different Data Types

A key feature of .tolist() is that it converts NumPy data types (like int64, float32) to their standard Python equivalents (int, float).

Python numpy转list的方法有哪些?-图3
(图片来源网络,侵删)
import numpy as np
# Array with various data types
arr_mixed = np.array([1, 2.5, 3+4j, True, 'a'])
# Convert to a list
list_mixed = arr_mixed.tolist()
print(f"NumPy Array: {arr_mixed}")
print(f"Data types in NumPy array: {arr_mixed.dtype}\n") # U21 means unicode string of length 21
print(f"Python List: {list_mixed}")
print(f"Data types in Python list:")
for item in list_mixed:
    print(f"  - {item} (type: {type(item).__name__})")

Output:

NumPy Array: ['1' '2.5' '(3+4j)' 'True' 'a']
Data types in NumPy array: <U21
Python List: [1, 2.5, (3+4j), True, 'a']
Data types in Python list:
  - 1 (type: int)
  - 2.5 (type: float)
  - (3+4j) (type: complex)
  - True (type: bool)
  - a (type: str)

Note: NumPy has to choose a common data type for all elements in an array. In this case, it converts everything to strings (<U21). The .tolist() method then converts these string representations back to their original Python types.


Alternative (But Not Recommended) Methods

While .tolist() is the best tool for the job, it's useful to know other ways and why they are less suitable.

Using the list() Constructor

You can pass the NumPy array directly to the list() constructor.

When it works (for 1D arrays):

import numpy as np
arr_1d = np.array([10, 20, 30])
my_list = list(arr_1d)
print(my_list)       # Output: [10, 20, 30]
print(type(my_list)) # Output: <class 'list'>

Why it's problematic (for multi-dimensional arrays): The list() constructor does not understand the concept of nested dimensions. It will iterate over the array's top-level elements (which are arrays themselves) and create a list of those array objects.

import numpy as np
arr_2d = np.array([[1, 2], [3, 4]])
# This will NOT create a list of lists
my_list_bad = list(arr_2d)
print(my_list_bad)
print(type(my_list_bad[0])) # The elements are still NumPy arrays!

Output:

[array([1, 2]), array([3, 4])]
<class 'numpy.ndarray'>

This is almost never what you want. Stick to .tolist() for multi-dimensional arrays.

Slicing with [:]

This is a common NumPy idiom that creates a copy of the array. If you then pass that copy to list(), it behaves the same way as above.

import numpy as np
arr_2d = np.array([[1, 2], [3, 4]])
# This creates a copy, then list() fails as above
my_list_bad = list(arr_2d[:])
print(my_list_bad)

Output:

[array([1, 2]), array([3, 4])]

This is less readable and less direct than using .tolist().


Summary: Which Method to Use?

Method Best For Pros Cons
arr.tolist() Almost all cases. The standard, recommended way. - Handles 1D, 2D, n-D arrays correctly.
- Converts data types to Python equivalents.
- Clear, readable, and idiomatic.
None for this specific task.
list(arr) Only simple 1D arrays. Simple syntax for 1D. - Fails spectacularly for multi-dimensional arrays, creating a list of arrays, not a list of lists.
list(arr[:]) Avoid for this purpose. Explicitly creates a copy before conversion. - Unnecessarily verbose.
- Still fails for multi-dimensional arrays.

Final Recommendation:

Always use numpy_array.tolist() to convert a NumPy array to a Python list. It is the correct, safe, and most Pythonic way to do it.

分享:
扫描分享到社交APP
上一篇
下一篇