numpy.recarray.tolist#

方法

recarray.tolist()#

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

將陣列資料的副本以(巢狀)Python 列表形式回傳。資料項目會透過 item 函式轉換為最接近的相容內建 Python 型別。

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

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

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

註解

陣列可以透過 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]]

此遞迴的基本情況是零維陣列

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