我想像这样定义一个没有初始化长度的二维数组。
Matrix = [][]
但它不工作...
我试过下面的代码,但它也是错误的。
Matrix = [5][5]
Error:
Traceback ...
IndexError: list index out of range
我的错误是什么?
从技术上讲,你正试图对一个未初始化的数组进行索引。在添加项目之前,你必须首先用列表初始化外层列表;Python 将此称为 "list comprehension"。
# 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",并希望得到一个非方形的矩阵。
你应该做一个列表的列表,最好的方法是使用嵌套的理解力。
>>> 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