numpy.ndarray.tolist#

方法

ndarray.tolist()#

將陣列以 a.ndim 層深度的巢狀 Python 純量列表回傳。

回傳陣列資料的副本,作為(巢狀)Python 列表。資料項目透過 item 函數轉換為最接近相容的內建 Python 類型。

如果 a.ndim 為 0,則由於巢狀列表的深度為 0,因此它根本不會是列表,而只是一個簡單的 Python 純量。

參數:
回傳值:
y物件,或物件列表,或物件列表的列表,或…

陣列元素的可能巢狀列表。

註解

陣列可以透過 a = np.array(a.tolist()) 重新建立,儘管這有時可能會損失精度。

範例

對於 1D 陣列,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'>

此外,對於 2D 陣列,tolist 遞迴地應用

>>> a = np.array([[1, 2], [3, 4]])
>>> list(a)
[array([1, 2]), array([3, 4])]
>>> a.tolist()
[[1, 2], [3, 4]]

此遞迴的基本情況是 0D 陣列

>>> a = np.array(1)
>>> list(a)
Traceback (most recent call last):
  ...
TypeError: iteration over a 0-d array
>>> a.tolist()
1