Numeric array and for loops problem

Tim Churches tchur at optushome.com.au
Tue Jan 7 12:05:33 EST 2003


On Mon, 2003-01-06 at 06:56, Stan wrote:
> Hi all
>  I've made the following pice of code
> 
> 		try:
> 			f = open(os.path.join("xxx", fname))
> 		except IOError:
> 			print "no such a file"
> 		else:
> 			lines = f.readlines()					
> 			worldy = len(lines)
> 			worldx = len(lines[0])/2
> 			worldarray = Numeric.zeros((worldy,worldx))
> 			y = -1 #***because arrays starts at 0***
> 			for line in lines:
> 				y += 1
> 				vals = split(line)
> 				x = -1  #***same as y***
> 				for val in vals:
> 					x += 1
> 					worldarray[x,y] = val
> 			f.close()
> 
> It should read some strings from a file and insert their value into
> worldarray
> The file is so strocturated:
> Some string of numbers (all same lenght) all separated by whitespace.
> But python give me this message error!!! I really can't understand
> where's the matter? It's not possible such an assignment?
> worldarray[x,y] = val
> ValueError: array too large for destination

You need to convert val into a numeric value before assigning it to your
Numeric array. Remember that split() is a string method, operating on
the string line, and returns a sequence of strings in vals. So val is a
string. eg 

worldarray[x,y] = int(val)

Its also a good idea to explicitly set the typecode of the array when
you create it, using the typecode= argument to the array constructors.

Tim C

> -- 
> http://mail.python.org/mailman/listinfo/python-list







More information about the Python-list mailing list