我使用了一个外部模块(libsvm),它不支持numpy数组,只支持元组、列表和字典。但是我的数据是在一个二维numpy数组中。我如何将其转换为pythonic方式,也就是没有循环的方式。
>>> 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
发布于 2012-03-15 22:34:40
您可以简单地将矩阵转换为带有matrix.tolist()
,proof的列表:
>>> 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'>
https://stackoverflow.com/questions/9721884
复制相似问题