Whats wrong with the following code?
using pythonWin I get the following error:
Traceback (most recent call last):
File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" ,
line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\Documents and Settings\Administrator\My
Documents\file_parser.py", line 16, in ?
rownum = range(eval(nrows))
TypeError: object doesn't support item assignment CODE
f = open('f:\input.dat')
feed= f.read()
lines = feed.split('\n')
ncols = lines[0].split()[1]
nrows = lines[1].split()[1]
xllcorner = lines[2].split()[1]
yllcorner = lines[3].split()[1]
cellsize = lines[4].split()[1]
NoData = lines[5].split()[1]
colnum = range(eval(ncols))
rownum = range(eval(nrows))
for r in rownum:
for c in colnum:
slope[r][c]= eval(lines[6+r].split()[c])
f.close()END OF CODE 3 1742
Matthew Walsh <ma********@gmail.com> wrote: Whats wrong with the following code? using pythonWin I get the following error:
Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Administrator\My Documents\file_parser.py", line 16, in ? rownum = range(eval(nrows)) TypeError: object doesn't support item assignment
CODE f = open('f:\input.dat') feed= f.read() lines = feed.split('\n') ncols = lines[0].split()[1] nrows = lines[1].split()[1] xllcorner = lines[2].split()[1] yllcorner = lines[3].split()[1] cellsize = lines[4].split()[1] NoData = lines[5].split()[1]
colnum = range(eval(ncols)) rownum = range(eval(nrows))
for r in rownum: for c in colnum: slope[r][c]= eval(lines[6+r].split()[c])
f.close()END OF CODE
Looks like the message is off by a few lines. The item assignment
you're trying to do is in the body of the nested for, and since 'slope'
isn't ever assigned anything anywhere it's hard to guess what it is, but
apparently its items don't support item assignment.
Alex
On 20 Oct 2004 13:27:40 -0700, ma********@gmail.com (Matthew Walsh) wrote: Whats wrong with the following code?
Why not print out the data it's using as it goes? That's only 5 lines.
There might be a clue.
using pythonWin I get the following error:
Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Administrator\My Documents\file_parser.py", line 16, in ? rownum = range(eval(nrows)) TypeError: object doesn't support item assignment
CODE f = open('f:\input.dat') feed= f.read() lines = feed.split('\n') ncols = lines[0].split()[1] nrows = lines[1].split()[1] xllcorner = lines[2].split()[1] yllcorner = lines[3].split()[1] cellsize = lines[4].split()[1] NoData = lines[5].split()[1]
Stylistically, that's a lot of re-typing. E.g., see below for alternative
Also, why not put all those on one line? Or don't you have control over input format?
colnum = range(eval(ncols)) rownum = range(eval(nrows))
the best way to convert from string to integer is int(thestring), not eval(thestring).
The latter risks bad surprises if thestring has not been verified safe. for r in rownum: for c in colnum: slope[r][c]= eval(lines[6+r].split()[c])
What is slope? Nested list representation of 2D array?
what is the format of the items on the line? Presumably numeric literals, but ints? floats?
I'll assume floats would be safe, but I special cased-NoData.
Have you considered making slope a list subclass instance that you can access your
named values from as well as slope[r][c] for data values, and initialize like
f = file('f:\input.dat'); slope = Slope(f) ? E.g., (not tested beyond what you see ;-)
----< slope.py >------------------------
class Slope(list):
"""
2D data container initialized from text line sequence or iterator yielding:
... ncols ...
... nrows ...
... xllcorner ...
... yllcorner ...
... cellsize ...
... NoData ...
<row 0>
<row 1>
<row nrows-1>
where a row is
col0value col1value col2value ... col<ncols-1>value
If the iterator is an open file, the caller is responsible for closing it.
"""
def __init__(self, lines):
lines = iter(lines)
for name in 'ncols nrows xllcorner yllcorner cellsize'.split():
setattr(self, name, int(lines.next().split()[1]))
self.NoData = lines.next().split()[1]
mx = []
for r in xrange(self.nrows):
mx.append([float(v) for v in lines.next().split()])
list.__init__(self, mx)
def __str__(self):
return '\n'.join(['<Slopes object:']+map(str, list(self))+['>'])
def test():
mx = Slope("""\
?? 3
?? 2
?? 111
?? 222
?? 333
?? NoDataToken??
0 1 2
3 4 5
""".splitlines())
for name in 'ncols nrows xllcorner yllcorner cellsize NoData'.split():
print '%10s: %r' % (name, getattr(mx, name))
print mx
for r in xrange(mx.nrows):
for c in xrange(mx.ncols):
print mx[r][c],
if __name__ == '__main__':
test()
----------------------------------------
I put ?? as place holders since I didn't know what you had there.
Result:
[18:39] C:\pywk\clp>slope.py
ncols: 3
nrows: 2
xllcorner: 111
yllcorner: 222
cellsize: 333
NoData: 'NoDataToken??'
<Slopes object:
[0.0, 1.0, 2.0]
[3.0, 4.0, 5.0]
0.0 1.0 2.0 3.0 4.0 5.0
Regards,
Bengt Richter
On Thu, 21 Oct 2004 01:41:32 GMT, bo**@oz.net (Bengt Richter) wrote:
[...] ----< slope.py >------------------------
[...] def __init__(self, lines): lines = iter(lines) for name in 'ncols nrows xllcorner yllcorner cellsize'.split(): setattr(self, name, int(lines.next().split()[1])) self.NoData = lines.next().split()[1] mx = [] for r in xrange(self.nrows): mx.append([float(v) for v in lines.next().split()]) list.__init__(self, mx) def __str__(self): return '\n'.join(['<Slopes object:']+map(str, list(self))+['>'])
I don't like that useless separate mx. Below seems better, since apparently the base class
supplies an initialized empty list (though I'm not sure exactly how that is implemented):
def __init__(self, lines):
lines = iter(lines)
for name in 'ncols nrows xllcorner yllcorner cellsize'.split():
setattr(self, name, int(lines.next().split()[1]))
self.NoData = lines.next().split()[1]
for r in xrange(self.nrows):
self.append([float(v) for v in lines.next().split()])
Always room for improvement ;-)
Regards,
Bengt Richter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: semarketing-request |
last post by:
>>>> This is a multi-part message in MIME format.
**** Command 'this' not recognized.
**** No valid commands found.
**** Commands must be in message BODY, not in HEADER.
**** Help for...
|
by: Will Stuyvesant |
last post by:
Here is a question about list comprehensions . The
question is dumb because I can do without ; but I am
posing the question because I am curious.
This:
>>> data = ,,]
>>> result =
>>> for...
|
by: David Bear |
last post by:
I have a file that contains lists -- python lists. sadly, these are not
pickled. These are lists that were made using a simple print list
statement.
Is there an easy way to read this file into a...
|
by: plmanikandan |
last post by:
Hi,
I am new to link list programming.I need to traverse from the end of
link list.Is there any way to find the end of link list without
traversing from start(i.e traversing from first to find the...
|
by: comp.lang.tcl |
last post by:
My TCL proc, XML_GET_ALL_ELEMENT_ATTRS, is supposed to convert an XML
file into a TCL list as follows:
attr1 {val1} attr2 {val2} ... attrN {valN}
This is the TCL code that does this:
set...
|
by: waldopat |
last post by:
Hi all,
I have an excel doc that has some information about various countries and I want to get a list of all the countries, which is in Column A. But, when I try to iterate over column A, I get...
|
by: cumupkid |
last post by:
II am trying to create a form that will allow me to upload photos to a folder in the site root directory and add the information to the mysql db at the same time.
I have created two forms, one...
|
by: A.Rocha |
last post by:
Hi,
I need save to text file a List<type>, but i dont wont serialize.
//
List<mytypemyList = new List<mytype>();
anyone can help me?
--
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
| |