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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

Use:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

我认为NumPy是最好的选择。如果您不想使用NumPy,上面是一个通用的。

其他回答

公认的答案是正确的,但我花了一段时间才明白,我也可以使用它创建一个完全空的数组。

l =  [[] for _ in range(3)]

结果

[[], [], []]

通常,go to模块是NumPy:

import numpy as np
   
# Generate a random matrix of floats
np.random.rand(cols,rows)

# Generate a random matrix of integers
np.random.randint(1, 10, size=(cols,rows))

我正在编写我的第一个Python脚本,我对方阵示例有点困惑,所以我希望下面的示例可以帮助您节省一些时间:

 # Creates a 2 x 5 matrix
 Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

因此

Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range

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

Matrix = {}

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

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

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

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

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

为便于阅读而重写:

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