在 NumPy 里,n.tolist()
方法能够把 NumPy 数组转换为 Python 列表。下面为你详细介绍其使用方法:
基本用法
该方法不需要任何参数,直接对 NumPy 数组调用即可。下面是一个简单的示例:
python
import numpy as np
# 创建一个 NumPy 数组
n = np.array([[1, 2, 3], [4, 5, 6]])
# 将 NumPy 数组转换为 Python 列表
python_list = n.tolist()
print(python_list) # 输出: [[1, 2, 3], [4, 5, 6]]
print(type(python_list)) # 输出: <class 'list'>
import numpy as np
# 创建一个 NumPy 数组
n = np.array([[1, 2, 3], [4, 5, 6]])
# 将 NumPy 数组转换为 Python 列表
python_list = n.tolist()
print(python_list) # 输出: [[1, 2, 3], [4, 5, 6]]
print(type(python_list)) # 输出: <class 'list'>
多维数组转换
对于多维数组,tolist()
会递归地把每个元素都转换为列表,最终形成嵌套列表。示例如下:
python
# 创建一个三维数组
n = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
python_list = n.tolist()
print(python_list)
# 输出: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
# 创建一个三维数组
n = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
python_list = n.tolist()
print(python_list)
# 输出: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
数据类型转换
在转换过程中,数组元素的数据类型会被转换为最接近的 Python 类型。例如:
- NumPy 的整数类型(像
np.int32
、np.int64
)会转换为 Python 的int
类型。 - NumPy 的浮点数类型(例如
np.float32
、np.float64
)会转换为 Python 的float
类型。 - NumPy 的布尔类型(
np.bool_
)会转换为 Python 的bool
类型。
下面是一个数据类型转换的示例:
python
n = np.array([1.5, 2.7], dtype=np.float32)
python_list = n.tolist()
print(python_list) # 输出: [1.5, 2.7]
print(type(python_list[0])) # 输出: <class 'float'>
n = np.array([1.5, 2.7], dtype=np.float32)
python_list = n.tolist()
print(python_list) # 输出: [1.5, 2.7]
print(type(python_list[0])) # 输出: <class 'float'>
与直接使用列表的区别
使用 tolist()
得到的是完全独立的 Python 列表,对该列表进行修改不会影响原来的数组。例如:
python
n = np.array([1, 2, 3])
python_list = n.tolist()
# 修改列表元素
python_list[0] = 100
print(python_list) # 输出: [100, 2, 3]
print(n) # 输出: [1 2 3](原数组未被修改)
n = np.array([1, 2, 3])
python_list = n.tolist()
# 修改列表元素
python_list[0] = 100
print(python_list) # 输出: [100, 2, 3]
print(n) # 输出: [1 2 3](原数组未被修改)
常见应用场景
tolist()
方法在以下场景中经常会用到:
- 需要将 NumPy 数组传递给只接受 Python 列表的函数。
- 要把数组数据保存为 JSON 格式(JSON 不支持 NumPy 数组类型)。
- 进行调试时,方便以列表形式查看数组内容。