我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
如果您希望能够将其视为2D阵列,而不是被迫根据列表进行思考(在我看来更自然),可以执行以下操作:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
结果是一个列表(不是NumPy数组),您可以用数字、字符串等覆盖各个位置。
其他回答
l=[[0]*(L) for _ in range(W)]
将快于:
l = [[0 for x in range(L)] for y in range(W)]
这是一个来自C、CPP和Java背景的初学者的代码
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
为什么这么长的代码,在Python中也是如此?
很久以前,当我不熟悉Python时,我看到了编写2D矩阵的单行答案,并告诉自己我不会再在Python中使用2D矩阵。(这些单行很吓人,它没有告诉我Python在做什么。还要注意,我不知道这些短手。)
我正在编写我的第一个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
如果在开始之前没有大小信息,请创建两个一维列表。
list 1: To store rows
list 2: Actual two-dimensional matrix
将整行存储在第一个列表中。完成后,将列表1追加到列表2中:
from random import randint
coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=[]
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
输出:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
为便于阅读而重写:
# 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)