将2D numpy的数组列表清单 [英] Convert 2d numpy array into list of lists

查看:151
本文介绍了将2D numpy的数组列表清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用外部模块( LIBSVM 的),它不支持numpy的阵列,只有元组,列表和类型的字典。但是我的数据是在2D numpy的数组。我怎样才能把它转换的Python的方式,又名不循环。

 >>>进口numpy的
>>>阵= numpy.ones((2,4))
>>> DATA_LIST =列表(阵列)
>>> DATA_LIST
[阵列([1,1,1,1]),阵列([1,1,1,1])]>>>类型(DATA_LIST [0])
<键入'numpy.ndarray'> #< =我不想要什么使用循环#非Python的方式
>>> newdata =名单()
>>>在DATA_LIST行:
...行=清单(行)
... newdata.append(线)
>>>类型(newdata [0])
<类型列表'> #&LT =我想要什么


解决方案

 >>>进口numpy的
>>>一个= numpy.ones((2,4))
>>>一个
阵列([1,1,1,1]
       [1.,1。,1.,1。]])
>>> a.tolist()
[1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0]]
>>>类型(a.tolist())
<类型列表'>
>>>类型(a.tolist()[0])
<类型列表'>

I use an external module (libsvm), which does not support numpy arrays, only tuples, lists and dicts. But my data is in a 2d numpy array. How can I convert it the pythonic way, aka without loops.

>>> import numpy
>>> array = numpy.ones((2,4))
>>> data_list = list(array)
>>> data_list
[array([ 1.,  1.,  1.,  1.]), array([ 1.,  1.,  1.,  1.])]

>>> type(data_list[0])
<type 'numpy.ndarray'>  # <= what I don't want

# non pythonic way using for loop
>>> newdata=list()
>>> for line in data_list:
...     line = list(line)
...     newdata.append(line)
>>> type(newdata[0])
<type 'list'>  # <= what I want

解决方案

>>> import numpy
>>> a = numpy.ones((2,4))
>>> a
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
>>> a.tolist()
[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]
>>> type(a.tolist())
<type 'list'>
>>> type(a.tolist()[0])
<type 'list'>

这篇关于将2D numpy的数组列表清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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