[英]How can I declare a 5x5 grid of numbers in Python?
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/ . 除了给出的答案-如果您需要使用Python处理2D(或更高维)数组,为此目的一个很好的库是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, ...). 其中,它使您可以在特定时刻轻松以适合您的任何逻辑形式对数组进行“重塑”(例如,可以将6个值的列表视为以下任意数组-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 创建一个5x5的零矩阵
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.