[Tutor] 2D array question [was (no subject)]

Alan Gauld alan.gauld at freenet.co.uk
Fri Aug 18 10:38:20 CEST 2006


> Mr. Kuhlman it says python is not configured for tk.

Gaarrgh! Why do linux distros do this? Stooopid...

You will need to fetch another version of Python with 
Tk support built in. Its a compile time option so you can 
either fetch the source an build it yourself or find a Suse 
package with Tk support already selected.

Its really stupid for Suse to do that, it only saves a tiny 
amount of space and means you can't run any programs 
based on Tkinter...

> but on another note does anyone know how to make a 2d array?

This should probably be a separate post.

Also can you change the subject line in your posts so people 
can fiind the thread easily. I've changed it on this one to pick 
up the 2D array issue....

A 2D array is just a table. There are several ways to do that 
in Python but the easiest is just a list of lists: Think of a chess 
game as an example where the boars is represented by 
an 8x8 2D array:

chessBoard = [
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0]
]

Now you can access the third row, 4th column with:

chessBoard[2][3]   # remember zero indexing!

Is that clear?

You can also use tuples similarly, or nested dictionaries.
A lot will depend on the data you are storing and how you 
want to access it.

Finally you can create a Class with bespoke methods to 
more closely model your problem, but the class will usaually 
have one of the above solutions internally anyhow!

HTH.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


More information about the Tutor mailing list