将NumPy数组转换为Python List结构?

问题:将NumPy数组转换为Python List结构?

如何将NumPy数组转换为Python列表(例如[[1,2,3],[4,5,6]]),并且速度相当快?

How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]] ), and do it reasonably fast?


回答 0

用途tolist()

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

请注意,这会将值从它们可能具有的任何numpy类型(例如np.int32或np.float32)转换为“最近兼容的Python类型”(在列表中)。如果要保留numpy数据类型,则可以在数组上调用list(),最后得到numpy标量列表。(感谢Mr_and_Mrs_D在评论中指出这一点。)

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the “nearest compatible Python type” (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you’ll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)


回答 1

如果numpy数组形状为2D,则numpy .tolist方法将生成嵌套列表。

如果需要平面列表,则可以使用以下方法。

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`

The numpy .tolist method produces nested lists if the numpy array shape is 2D.

if flat lists are desired, the method below works.

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`

回答 2

tolist()熊猫说,即使遇到嵌套数组,也可以正常工作DataFrame

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

回答 3

someList = [list(map(int, input().split())) for i in range(N)]

someList = [list(map(int, input().split())) for i in range(N)]


回答 4

c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())

c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())