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

查看:83
本文介绍了将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(),最后得到一个

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天全站免登陆