將NumPy數組轉換為Python List結構?



Answers

numpy .tolist方法在numpy數組形狀為2D時生成嵌套數組。

如果需要扁平列表,下面的方法工作。

import numpy as np
from itertools import chain

a = [1,2,3,4,5,6,7,8,9]
print type(a), len(a), a
npa = np.asarray(a)
print type(npa), npa.shape, "\n", npa
npa = npa.reshape((3, 3))
print type(npa), npa.shape, "\n", npa
a = list(chain.from_iterable(npa))
print type(a), len(a), a`
Question

如何將NumPy數組轉換為Python列表(例如[[1,2,3],[4,5,6]] ),並合理快速地執行?






Links



Tags

python python   numpy