tags:

views:

111

answers:

4

How would I declare this? I'm thinking something along the lines of:

boardPieces = ["A","O","A"
               "A", "A", "O"
              ]
+1  A: 
[[0] * 5 for x in range(5)]

or

[[0 for x in range(5)] for y in range(5)]

The first will only work with immutable types, while the second will work with any type.

Ignacio Vazquez-Abrams
Don't understand why this was downvoted.
Adam Bernier
I didn't down-vote it. But I think it was down-voted because the first example doesn't work. It creates an array like: [ [0], [0], [0], ...]
Wallacoloo
Ah, yes, fixed now.
Ignacio Vazquez-Abrams
+4  A: 

I'm assuming a 2d matrix? Something like this should work.

boardPieces = [["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"],["A","O","A","A", "A"]]
Snazzer
A: 

Just do like this.

[["A","O","A","O","A"],[...],[...],[...],[...]]
S.Mark
+3  A: 

In addition to the answers given - if you need to do work with 2D (or higher dimension) arrays in Python, a very good library for this purpose is Numpy - http://numpy.scipy.org/.

Among others, it lets you easily "reshape" an array in whatever logical form fits you at a particular moment (for example, an list of 6 values can be treated as any of the following arrays - 1x6, 2x3, 3x2, ...).

The output of this code -

import numpy

boardPieces = numpy.array( [ "A", "O", "A", "A", "A", "O" ], numpy.character )
boardPieces = boardPieces.reshape( [ 2, 3 ] )
print boardPieces
boardPieces = boardPieces.reshape( [ 3, 2 ] )
print boardPieces

Would be -

[['A' 'O' 'A']
 ['A' 'A' 'O']]
[['A' 'O']
 ['A' 'A']
 ['A' 'O']]

Might not be suitable for your particular use-case, but can serve as a reference for others.

Hexagon