How would I declare this? I'm thinking something along the lines of:
boardPieces = ["A","O","A"
"A", "A", "O"
]
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"]]
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.
[[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.
就这样吧
[["A","O","A","O","A"],[...],[...],[...],[...]]
Creating a 5x5 matrix of zeroes
ls = [[0]*5]*5
print(ls)
Output:
[[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]]
Similarly a matrix of string type values
ls = [['A','O','A','A','A']]*5
print(ls)
Output:
[['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']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.