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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

试试看:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

其他回答

为便于阅读而重写:

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

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

如果你只需要一个二维容器来容纳一些元素,你可以方便地使用字典来代替:

Matrix = {}

然后您可以执行以下操作:

Matrix[1,2] = 15
print Matrix[1,2]

这是因为1,2是一个元组,您将其用作索引字典的键。结果类似于哑稀疏矩阵。

如osa和Josap Valls所示,您还可以使用Matrix=collections.defaultdict(lambda:0),以便丢失的元素具有默认值0。

Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,只应在代码的非性能关键部分使用。

如果您想创建一个二维矩阵,其维度由两个变量定义,并使用其所有元素的默认值对其进行初始化。您可以使用以下简单语法

n_rows=3
n_cols=4
aux_matrix= [[1]*n_cols]*n_rows

Use:

matrix = [[0]*5 for i in range(5)]

第一个维度的*5有效,因为在这个级别上数据是不可变的。