简体   繁体   中英

How to convert a numpy.ndarray type into a list?

I want to read a matfile in python and then export the data in a database. in order to do this I need to have the data type as list in python. I wrote the code below:

import scipy.io as si
import csv

a = si.loadmat('matfilename')
b = a['variable']                
list1=b.tolist()  

The variable has 1 row and 15 columns. when I print list1 , I get the answer below: (It is indeed a list, but a list that contains only one element. It means when I call list1[0], I get the same result.):

[[array(['A'], 
  dtype='<U13'), array(['B'], 
  dtype='<U14'), array(['C'], 
  dtype='<U6'), array(['D'], 
  dtype='<U4'), array(['E'], 
  dtype='<U10'), array(['F'], 
  dtype='<U13'), array(['G'], 
  dtype='<U11'), array(['H'], 
  dtype='<U9'), array(['I'], 
  dtype='<U16'), array(['J'], 
  dtype='<U18'), array(['K'], 
  dtype='<U16'), array(['L'], 
  dtype='<U16'), array(['M'], 
  dtype='<U16'), array(['N'], 
  dtype='<U14'), array(['O'], 
  dtype='<U13')]]

While the form that I expect is:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']

Does anyone know what the problem is?

To my experience, that is just like MATLAB files are structured, only nested arrays.

You can create the list yourself:

>>> [x[0][0] for x in list1[0]]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM