[Tutor] Table like array in Python

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Wed Mar 26 12:03:06 CET 2008


Gloom Demon schreef:
> Hello :-)
> 
> I am reading Ivan van Leiningem "Learn Python in 24 hours" and I am 
> having problems understanding the way arrays work in Python. I used to 
> know Pascal and arrays there were tablelike.
> 
> 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 ....................

That is an array of records. In Pascal you can also have e.g. an array 
of integers, and it is a sequential list just as in Python. What makes 
it table-like is that you have an array not of scalars but of records.

> 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 ........................

You could do it like that, but there are better ways. You could make a 
list of tuples, which would be more or less equivalent to your Pascal 
array of records. A simple example, presuming you read the values from a 
file:

lst = []
for line in countryfile:
   country, year, amount = line.split()
   year = int(year)
   amount = float(amount)
   lst.append((country, year, amount))

That would look like:

[
   ('US', 2006, 22.10),
   ('US', 2007, 23.45)
   ...
]

Then you could scan through it like this:

for record in lst:
   if record[0] == 'US':
     ...


-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

Roel Schroeven



More information about the Tutor mailing list