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

Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围


当前回答

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

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

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

其他回答

从技术上讲,您正在尝试对未初始化的数组进行索引。在添加项目之前,必须先用列表初始化外部列表;Python调用此“列表理解”。

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)] 

#您现在可以向列表中添加项目:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

注意,矩阵是“y”地址主,换句话说,“y索引”在“x索引”之前。

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

尽管您可以根据自己的意愿命名它们,但我这样看是为了避免索引中可能出现的一些混淆,如果您对内部和外部列表都使用“x”,并且希望使用非方形矩阵。

如果你真的想要一个矩阵,你最好使用numpy。numpy中的矩阵运算通常使用二维数组类型。创建新阵列有多种方法;其中最有用的是zeros函数,它接受一个形状参数并返回一个给定形状的数组,值初始化为零:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 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.]])

以下是创建二维数组和矩阵的一些其他方法(为了紧凑,去掉了输出):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy也提供了一种矩阵类型,但它不再推荐用于任何用途,将来可能会从numpy中删除。

Use:

matrix = [[0]*5 for i in range(5)]

第一个维度的*5有效,因为在这个级别上数据是不可变的。

使用NumPy,可以如下初始化空矩阵:

import numpy as np
mm = np.matrix([])

然后像这样附加数据:

mm = np.append(mm, [[1,2]], axis=1)

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

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