繁体   English   中英

将 NumPy 数组转换为 Python 列表

[英]Convert NumPy array to Python list

如何将NumPy数组转换为 Python 列表?

使用tolist()<\/code><\/a> :

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

如果 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`

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

list(c.flatten())

即使遇到嵌套数组, tolist()也能正常工作,比如 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))

另外一个选择

c.ravel()
# or
c.ravel().tolist()

也有效。

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

将数组转换为列表的最简单方法是使用 numpy package:

import numpy as np
#2d array to list
2d_array = np.array([[1,2,3],[8,9,10]])
2d_list = 2d_array.tolist()

要检查数据类型,您可以使用以下命令:

type(object)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM