2012-03-15 11 views
60

Utilizo un módulo externo (libsvm), que no admite matrices numpy, solo tuplas, listas y dicts. Pero mis datos están en un 2d numpy array. ¿Cómo puedo convertirlo en la forma pitónica, también conocida como sin bucles?Convierta 2d numpy array en la lista de listas

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

Es posible que desee echa un vistazo a scikit-learn, que incluye una envoltura LibSVM que hace manejar matrices numpy forma nativa. http://scikit-learn.org/stable/modules/classes.html#module-sklearn.svm –

Respuesta

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