Multidimensional arrays/lists

Ethan Furman ethan at stoneleaf.us
Mon Sep 28 15:27:23 EDT 2009


Simon Forman wrote:
> On Sun, Sep 27, 2009 at 12:40 PM, Someone Something
> <fordhaivat at gmail.com> wrote:
> 
>>I'm trying to write a little tic-tac-toe program I need a array/list such
>>that I can represent the tic tac toe board with an x axis and y axis and i
>>can access each square to find out whether there is an X or an O. I have
>>absolutely no idea how to do this in python and I really, really, don't want
>>to do this is C.
>>
>>--
>>http://mail.python.org/mailman/listinfo/python-list
>>
>>
> 
> 
> You can use tuples as keys in a dict
> 
> R = range(3)
> 
> board = {}
> 
> # Initialize the board.
> for x in R:
>     for y in R:
>         board[x, y] = 'O'
> 
> 
> def board_to_string(b):
>     return '\n'.join(
>                ' | '.join(b[x, y] for x in R)
>                for y in R
>                )
> 
> 
> 
>>>>print board_to_string(board)
> 
> O | O | O
> O | O | O
> O | O | O
> 
> 
>>>>board[0, 1] = 'X'
>>>>print board_to_string(board)
> 
> O | O | O
> X | O | O
> O | O | O

You might not want to start out with 'O' already being everywhere, 
though.  ;-)

~Ethan~



More information about the Python-list mailing list