[Tutor] The concept of string arrays
Erik Price
erikprice@mac.com
Mon Feb 3 20:16:04 2003
On Monday, February 3, 2003, at 07:30 PM, andy surany wrote:
> I'm reading an Excel file into memory. The values are all strings. My
> no
> frills approach to doing this was to simply set up a list, read the
> values from a file, and append the list. Each element is then
> referenced
> via position. For example,
>
> First_Name Last_Name Address Date_of_Birth
>
> would be input as follows:
>
> client.append(First_Name)
> client.append(Last_Name)
> client.append(Address)
> client.append(Fate_of_Birth)
>
> now if I want to reference the 45th row in the cell, I would start at
> position 45*4.
>
> This works - but I know that there have to be more elegant solutions. I
> tried creating a 4 dim array - but found that string types were not
> allowed. Is it possible to create a multi dimensional list or tuple?
> or????
Elegance is probably in the eye of the beholder, but I personally hate
multi-dimensional arrays. Maybe they're helpful if you're programming
in C, or if you're concerned with performance, I have no idea. Why not
just create a couple of objects to represent the data you're working
with?
My own approach would be to create a Record or Row class that
represents a row of the spreadsheet. It would have four fields, each
named after one of the columns. You could write another object called
SpreadSheet which could serve as a handy wrapper object around a list
(or perhaps a tuple if you're doing read-only work), with some
convenience methods.
The Record object is probably self-explanatory, but the SpreadSheet
class might look something like:
class SpreadSheet:
def __init__():
this.recordlist = []
def get_records:
return this.recordlist
def get_record(index):
return this.recordlist[index]
def append_record(record):
this.recordlist.append(record)
def read_record():
...etc...
Then, when you want to use your classes, you can do something to the
effect of:
f = open("spreadsheet.xls")
ss = new SpreadSheet()
for i in f.readlines():
r = new Record(i)
ss.append(r)
or something like that. (I haven't written Python in a long time so my
syntax may be incorrect, but it's to give you the gist of what one
person considers elegant.)
As I said before, it's a matter of taste, but I find that designs which
make use of objects help clarify what is going on in the program and
make for a more elegant design.
Erik
--
Erik Price
email: erikprice@mac.com
jabber: erikprice@jabber.org