[Tutor] Table like array in Python

Kent Johnson kent37 at tds.net
Wed Mar 26 11:41:20 CET 2008


Gloom Demon wrote:

> Example (cost of something in different countries by different years)
> 
> Record1 US 2006 22.10
> Record2 US 2007 23.45
> Record3 UK 2007 22.90
> ..................................
> RecordN ....................
> 
> So I could read the record, see if the name of the country in the first 
> cell was what I was looking for and either continue working with the 
> record or resume searching.

Where are the records coming from? A file or database?
> 
> However in Python, if I understand correctly this example would look 
> like this:
> 
> US 2006 22.10 US 2007 23.45 UK 2007 22.90 ........................

If the data is in a file, and you read the file using file.read(), then 
you will get the full contents in memory in a single string.
> 
> This means that I have to keep a lot of unnesessary information in RAM, 
> not to mention that I would have to scan through the whole array instead 
> of scanning just the required cell. 
> 
> Could anyone please direct me to a good description of working with 
> arrays in Python?

Arrays are called lists in Python, they are covered in every tutorial.
But I think maybe it is files that you need help with.

You can read files line by line. One way is to use a for loop, for example,

f = open('records.txt')
for line in f: # the contents of each line in turn will be put in 'line'
   data = line.split() # split the line at spaces
   if data[1] == 'US':
     # process line for US

Kent


More information about the Tutor mailing list