Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
矩阵生成器python索引分配列表超出范围_Python_Matrix_Indexing - Fatal编程技术网

矩阵生成器python索引分配列表超出范围

矩阵生成器python索引分配列表超出范围,python,matrix,indexing,Python,Matrix,Indexing,下面是我写的代码。它说列表分配索引超出范围。我似乎不知道我哪里出了问题。也许有人可以详细说明错误在哪里 def genarator(x, y): square = x * y matrix = [[]] matrix2 = [] i = 0 while square > 0: j = 0 while x > j: matrix[i][j] = int(raw_input("Ent

下面是我写的代码。它说列表分配索引超出范围。我似乎不知道我哪里出了问题。也许有人可以详细说明错误在哪里

def genarator(x, y):
    square = x * y
    matrix = [[]]
    matrix2 = []

    i = 0    
    while square > 0:
        j = 0
        while x > j:
            matrix[i][j] = int(raw_input("Enter the matrix number"))
            j = 1
        i = 1
        square = -square
        matrix2 = matrix2 + matrix

    return matrix2


def main():    
    matrix3 = []
    x = int(raw_input("Enter the width of your matrix"))
    y = int(raw_input("Enter the Length of your matrix"))
    matrix3 = genarator(x, y)
    print(matrix3)
    return 0

main()
###编辑我解决了这个问题 def发生器(x,y):


main()

如果您尝试以下代码段:

x = []
x[0] = 4
您将看到有一个错误。原因是
x[0]
尚未定义,因此无法修改。要修复错误,您必须在修改列表之前将某些内容附加到列表中:

def genarator(x, y):
    square = x * y
    matrix = [[]]
    matrix2 = []

    i = 0    
    while square > 0:
        matrix.append([])
        j = 0
        while x > j:
            matrix[-1].append(int(raw_input("Enter the matrix number")))
            j = 1
        i = 1
        square = -square
        matrix2 = matrix2 + matrix

    return matrix2
我还修改了索引,因为
-1
将为您提供最后一项,这是您想要的

x = []
x[0] = 4
def genarator(x, y):
    square = x * y
    matrix = [[]]
    matrix2 = []

    i = 0    
    while square > 0:
        matrix.append([])
        j = 0
        while x > j:
            matrix[-1].append(int(raw_input("Enter the matrix number")))
            j = 1
        i = 1
        square = -square
        matrix2 = matrix2 + matrix

    return matrix2