[Tutor] reading a string into an array

Kent Johnson kent37 at tds.net
Sat May 31 23:11:21 CEST 2008


On Sat, May 31, 2008 at 3:43 PM, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I am trying to read a long string of values separated by a backslash into an
> array of known size.
>
> Here is my attempt,
>
> from numpy import *
> ay, ax = 384, 512
> a = zeros([ay, ax])
> for line in open('out.out'):
>     data = line.split('\\')

Are you trying to accumulate all the lines into data? If so you should use
data = []
for line in open('out.out'):
  data.extend(line.split('\\'))

> k = 0
> for i in range(ay):
>     for j in range(ax):
>         a[i, j] = data[k]
>         k+=1
> but, I receive the following error.
>
> Traceback (most recent call last):
>   File "C:/Users/bryan/Desktop/dose_array.py", line 13, in <module>
>     a[i, j] = data[k]
> ValueError: setting an array element with a sequence.

I think this is because data is a list of strings, not numbers. Change
my line above to
data.extend(int(i) for i in line.split('\\'))

But you don't have to create your array by copying every item. It is
numpy, after all! I think this will work:
data = []
for line in open('out.out'):
  data.extend(int(i) for i in line.split('\\'))

a = array(data)
a.shape = (384, 512)

Kent


More information about the Tutor mailing list