将2d numpy数组转换为列表列表

2024-09-23 04:35:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个外部模块(libsvm),它不支持numpy数组,只支持元组、列表和dict。但是我的数据是在一个2d的numpy数组中。我怎么能把它转换成Python的方式,又称没有循环。

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

Tags: 模块numpy列表fordatatypeline数组
1条回答
网友
1楼 · 发布于 2024-09-23 04:35:11

您可以简单地使用matrix.tolist()将矩阵强制转换为列表,证明:

>>> 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'>

相关问题 更多 >