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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

l=[[0]*(L) for _ in range(W)]

将快于:

l = [[0 for x in range(L)] for y in range(W)] 

其他回答

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

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

我在逗号分隔的文件中阅读如下:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

列表“data”是带有索引数据[row][col]的列表列表

为便于阅读而重写:

# 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)

使用列表:

matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

通过使用dict:您还可以将这些信息存储在哈希表中,以便快速搜索,例如

matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};

矩阵['1']将在O(1)时间内给出结果

*nb:你需要处理哈希表中的冲突

如果要创建空矩阵,正确的语法是

matrix = [[]]

如果你想生成一个大小为5、填充有0的矩阵,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]