如何定义二维数组?

905 投票
30 回答
2980569 浏览
提问于 2025-04-16 21:21

我想定义一个没有初始化长度的二维数组,像这样:

Matrix = [][]

但是这样会出现一个错误:

IndexError: 列表索引超出范围

30 个回答

404

这里有一种更简洁的方式来初始化一个列表的列表:

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]]
481

如果你真的想要一个矩阵,使用 numpy 可能会更好。numpy 中的矩阵操作通常使用一种有两个维度的数组类型。创建新数组的方法有很多,其中最有用的一种是 zeros 函数,它需要一个形状参数,并返回一个指定形状的数组,所有的值都初始化为零:

>>> 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 中移除。

1243

你实际上是在尝试访问一个还没有初始化的数组。你需要先把外面的列表初始化为列表,然后才能添加项目;在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”,而且想要一个非方形的矩阵,就会比较麻烦。

撰写回答