LOADING DATA INTO ARRAYS

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Jul 9 13:56:09 EDT 2003


>>>>> "satish" == satish k chimakurthi <skchim0 at engr.uky.edu> writes:

    satish> I have written the following code which is not working for
    satish> some reason.  Can anyone suggest any changes:
[snip]
    satish>  xval,yval=string.split(line) ValueError: unpack list of
    satish> wrong size

The problem is with this line of code.

     xval,yval=string.split(line)

As the error indicates you are unpacking the results of the split
(which has 3 elements x,y,z) into 2 variables xval, yval.  You need to
do

   xval, yval, zval = line.split()

But then xval, yval and zval are strings and I bet you want them to be
floats.  So this would be better

   xval, yval, zval = map(float, line.split())

Finally, if you are doing number crunching, you will be much happier
with Numeric http://pfdubois.com/numpy/.  If holding the whole list in
memory is not a problem before initializing to array, you can do

  from Numeric import array
  a = array([float(val) for val in line.split() 
                        for line in file('myfile.dat')])

This uses list comprehensions rather than map to do the float
conversions but it's the same idea.

Now you can access the first row with a[0], or the first column with
a[:,0], etc....

Numeric comes with lots of support for analysis, etc...  In addition,
many of the python plotting packages and other analysis packages are
designed to work with Numeric.

JDH





More information about the Python-list mailing list