如何在Python中定义二维数组

2024-03-29 12:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想定义一个没有初始化长度的二维数组,如下所示:

Matrix = [][]

但它不起作用。。。

我试过下面的代码,但也错了:

Matrix = [5][5]

错误:

Traceback ...

IndexError: list index out of range

我的错是什么?


Tags: of代码index定义错误range数组out
3条回答

以下是初始化列表列表的简短表示法:

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

从技术上讲,您试图为未初始化的数组编制索引。在添加项之前,必须首先用列表初始化外部列表;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”,并且希望使用非正方形矩阵。

如果您真的需要一个矩阵,那么最好使用numpynumpy中的矩阵运算通常使用二维数组类型。创建新数组的方法有很多;最有用的方法之一是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还提供了matrix类型。它不太常用,有些人使用它。但它对于从Matlab和其他环境中来到numpy的人很有用。我想我应该把它包括进去,因为我们在讨论矩阵!

>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
        [3, 4]])

下面是一些创建二维数组和矩阵的其他方法(为了紧凑性而删除输出):

numpy.matrix('1 2; 3 4')                 # use Matlab-style syntax
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.ndarray((5, 5))                    # use the low-level constructor

相关问题 更多 >