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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5

注意这个简短的表达,请参见@F.J的答案中的完整解释

其他回答

要声明一个零(1)矩阵:

numpy.zeros((x, y))

e.g.

>>> numpy.zeros((3, 5))
    array([[ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

或numpy.ones((x,y))例如

>>> np.ones((3, 5))
array([[ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.]])

甚至三维都是可能的。(http://www.astro.ufl.edu/~warner/prog/python.html请参见-->多维数组)

可以通过将两个或多个方括号或第三个方括号([],用逗号分隔)与方括号嵌套来创建一个空的二维列表,如下所示:

Matrix = [[], []]

现在假设您想将1附加到矩阵[0][0],然后键入:

Matrix[0].append(1)

现在,键入矩阵并按Enter键。输出将为:

[[1], []]

如果您输入以下语句

Matrix[1].append(1)

那么矩阵将是

[[], [1]]

在Python中,您将创建一个列表列表。您不必提前声明维度,但可以这样做。例如:

matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)

现在矩阵[0][0]==2,矩阵[1][0]==3。您还可以使用列表理解语法。本示例使用它两次来构建“二维列表”:

from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

你应该列出一个列表,最好的方法是使用嵌套的理解:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(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]]

在您的[5][5]示例中,您正在创建一个包含整数“5”的列表,并尝试访问其第5项,这自然会引发IndexError,因为没有第5项:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

为便于阅读而重写:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)