将二维 numpy 数组转换为列表列表 [英] Convert 2d numpy array into list of lists
本文介绍了将二维 numpy 数组转换为列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了一个外部模块(libsvm),它没有支持 numpy 数组,只有元组、列表和字典.但我的数据在一个二维 numpy 数组中.我怎样才能将它转换为 pythonic 方式,也就是没有循环.
<预><代码>>>>导入 numpy>>>数组 = numpy.ones((2,4))>>>数据列表 = 列表(数组)>>>数据列表[数组([ 1., 1., 1., 1.]), 数组([ 1., 1., 1., 1.])]>>>类型(数据列表[0])<输入'numpy.ndarray'># <=我不想要的# 使用for循环的非pythonic方式>>>新数据=列表()>>>对于 data_list 中的行:... 行 = 列表(行)... newdata.append(line)>>>类型(新数据[0])<输入列表"># <=我想要的 解决方案
你可以用 matrix.tolist()
简单地将矩阵转换为列表,证明:
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
解决方案
You can simply cast the matrix to list with 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'>
这篇关于将二维 numpy 数组转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文