我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
如果您想创建一个二维矩阵,其维度由两个变量定义,并使用其所有元素的默认值对其进行初始化。您可以使用以下简单语法
n_rows=3
n_cols=4
aux_matrix= [[1]*n_cols]*n_rows
其他回答
为便于阅读而重写:
# 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 = {}
可以通过两种方式定义键和值:
matrix[0,0] = value
or
matrix = { (0,0) : value }
结果:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
试试看:
rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
my_list.append(list(map(int, input().split())))
如果您希望能够将其视为2D阵列,而不是被迫根据列表进行思考(在我看来更自然),可以执行以下操作:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
结果是一个列表(不是NumPy数组),您可以用数字、字符串等覆盖各个位置。
如果您需要具有预定义数字的矩阵,可以使用以下代码:
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]