我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这行不通...
我已经尝试过下面的代码,但是它也是错误的:
Matrix = [5][5]
错误:
Traceback ...
IndexError: list index out of range
我怎么了
从技术上讲,您正在尝试索引未初始化的数组。您必须先使用列表初始化外部列表,然后再添加项目。 Python 将其称为 “列表理解”。
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)]
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
请注意,矩阵是 “y” 地址主地址,换句话说,“y 索引” 位于 “x 索引” 之前。
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
尽管您可以根据需要命名它们,但是如果您对内部列表和外部列表都使用 “x”,并且希望使用非平方矩阵,那么我会以这种方式来避免因索引而引起的混淆。
如果您真的想要一个矩阵,最好使用numpy
。 numpy
矩阵运算最常使用具有二维的数组类型。有很多方法可以创建一个新数组。最有用的zeros
函数,该函数采用 shape 参数并返回给定形状的数组,其值初始化为零:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 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.]])
这是创建二维数组和矩阵的其他一些方法(为了紧凑起见,删除了输出):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy
提供matrix
类型,但是 不再建议将其用于任何用途,将来可能会从numpy
这是用于初始化列表列表的简短表示法:
matrix = [[0]*5 for i in range(5)]
不幸的是,将其缩短为5*[5*[0]]
并不会真正起作用,因为最终会得到同一列表的 5 个副本,因此,当您修改其中一个副本时,它们都会改变,例如:
>>> matrix = 5*[5*[0]]
>>> matrix
[[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]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]