我使用外部模块(libsvm),它不支持numpy数组,只支持元组,列表和dicts。但是我的数据是2d 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
答案 0 :(得分:108)
>>> 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'>