[Tutor] simple question about lists
Bill Mill
bill.mill at gmail.com
Tue Jul 20 22:20:24 CEST 2004
Or, if you want to use list comprehensions to be in with the "cool
programmers", you could do:
def getEmptyBoard():
return [['.'] * 3 for i in range(3)]
Peace,
Bill Mill
On Tue, 20 Jul 2004 11:16:39 -0700 (PDT), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Tue, 20 Jul 2004, Andy wrote:
>
> > Hello all, I'm getting ready to teach myself python. I'm going to
> > convert an old tic tac toe game I wrote in C to get my feet wet. One
> > question though, in C I could set up a multi dimensional array by doing
> >
> > char board[3][3]
> >
> > I can't do multi dimensional lists in python can I? Am I right in
> > thinking that I would need to either use a one dimensional list or get
> > something like numeric to do this? Thanks in advance.
>
>
> Hi Andy,
>
> Yes, multidimensional lists are possible. The initialization is a little
> funny, though. Let me write the C equivlent first, and then a close
> Python translation to it.
>
> In C, we might do something like this:
>
> ###
> /*** Returns a 3x3 array of characters **/
> char** mallocEmptyBoard() {
> int i;
> int j;
> char** board = malloc(sizeof(char*) * 3);
> for(i = 0; i < 3; i++) {
> board[i] = malloc(sizeof(char) * 3);
> for(j = 0; j < 3; j++) {
> board[i][j] = '.';
> }
> }
> return board;
> }
> ###
>
> In Python, we'd have similar code, but with a little less typing:
>
> ###
> def getEmptyBoard():
> board = [None] * 3
> for i in range(3):
> board[i] = ['.', '.', '.']
> return board
> ###
>
> Does this make sense?
>
> There's an entry in the Python FAQ that talks about this a little more:
>
> http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list
>
> Good luck!
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list