将 NumPy 数组转换为 Python List 结构? [英] Converting NumPy array into Python List structure?

查看:28
本文介绍了将 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?

推荐答案

使用 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 在评论中指出这一点.)

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.)

这篇关于将 NumPy 数组转换为 Python List 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆