我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
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,上面是一个通用的。
其他回答
试试看:
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中创建矩阵的代码片段:
# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))
# initialize the list
l=[[0]*cols for i in range(rows)]
# fill some random values in it
for i in range(0,rows):
for j in range(0,cols):
l[i][j] = i+j
# print the list
for i in range(0,rows):
print()
for j in range(0,cols):
print(l[i][j],end=" ")
如果我错过了什么,请提出建议。
如果您希望能够将其视为2D阵列,而不是被迫根据列表进行思考(在我看来更自然),可以执行以下操作:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
结果是一个列表(不是NumPy数组),您可以用数字、字符串等覆盖各个位置。
可以通过将两个或多个方括号或第三个方括号([],用逗号分隔)与方括号嵌套来创建一个空的二维列表,如下所示:
Matrix = [[], []]
现在假设您想将1附加到矩阵[0][0],然后键入:
Matrix[0].append(1)
现在,键入矩阵并按Enter键。输出将为:
[[1], []]
如果您输入以下语句
Matrix[1].append(1)
那么矩阵将是
[[], [1]]