numpy.ndarray.tolist#
方法
- ndarray.tolist()#
将数组作为深度为
a.ndim的嵌套 Python 标量列表返回。将数组数据副本作为(嵌套的)Python 列表返回。数据项通过
item方法转换为最接近的兼容内置 Python 类型。如果
a.ndim为 0,那么由于嵌套列表的深度为 0,它将不是列表,而是一个简单的 Python 标量。- 参数:
- none
- 返回:
- yobject,或 object 列表,或 object 列表的列表,或…
可能的嵌套数组元素列表。
备注
可以通过
a = np.array(a.tolist())重新创建数组,尽管这有时可能会丢失精度。示例
对于一维数组,
a.tolist()几乎与list(a)相同,只是tolist会将 numpy 标量转换为 Python 标量。>>> import numpy as np >>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [np.uint32(1), np.uint32(2)] >>> type(a_list[0]) <class 'numpy.uint32'> >>> a_tolist = a.tolist() >>> a_tolist [1, 2] >>> type(a_tolist[0]) <class 'int'>
此外,对于二维数组,
tolist会递归应用。>>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]]
此递归的基础情况是 0 维数组。
>>> a = np.array(1) >>> list(a) Traceback (most recent call last): ... TypeError: iteration over a 0-d array >>> a.tolist() 1