3 回答

TA貢獻1853條經驗 獲得超6個贊
嚴格地說,您正在嘗試索引未初始化的數組。在添加項目之前,必須先用列表初始化外部列表;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
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
雖然你可以按你的意愿命名它們,但我這樣看待它是為了避免索引時可能出現的一些混亂,如果你對內部和外部列表都使用“x”,并且想要一個非平方矩陣的話。

TA貢獻1951條經驗 獲得超3個贊
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
matrix
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

TA貢獻2051條經驗 獲得超10個贊
下面是初始化列表的一個較短的符號:
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]]
添加回答
舉報