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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

你应该列出一个列表,最好的方法是使用嵌套的理解:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

在您的[5][5]示例中,您正在创建一个包含整数“5”的列表,并尝试访问其第5项,这自然会引发IndexError,因为没有第5项:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

其他回答

我在逗号分隔的文件中阅读如下:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

列表“data”是带有索引数据[row][col]的列表列表

我正在编写我的第一个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

下面是在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=" ")

如果我错过了什么,请提出建议。

如果要创建空矩阵,正确的语法是

matrix = [[]]

如果你想生成一个大小为5、填充有0的矩阵,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]

输入矩阵和打印的用户定义功能

def inmatrix(m,n):
    #Start function and pass row and column as parameter
    a=[] #create a blank matrix
    for i in range(m): #Row input
        b=[]#blank list
        for j in range(n): # column input
            elm=int(input("Enter number in Pocket ["+str(i)+"]["+str(j)+"] ")) #Show Row And column  number 
            b.append(elm) #add value to b list
        a.append(b)# Add list to matrix
    return  a #return Matrix 

def Matrix(a): #function for print Matrix
    for i in range(len(a)): #row
        for j in range(len(a[0])): #column
            print(a[i][j],end=" ") #print value with space
        print()#print a line After a row print

m=int(input("Enter number of row")) #input row
n=int(input("Enter number of column"))
a=inmatrix(m,n) #call input matrix function 

print("Matrix is ... ")

Matrix(a) #print matrix function