Matrix Generator python索引分配列表超出范围

时间:2016-02-20 01:21:36

标签: python matrix indexing

以下是我编写的代码。它说列表分配指数超出范围。我似乎无法弄清楚我在哪里出错了。也许有人可以详细说明错误的位置。

matrix = [[0 for i in range(x)] for j in range(y)]

turns = x

i = 0

j = 0

while turns > 0:

    while i < x:

        while j < y:

            matrix[i][j] = int(raw_input("Enter Array values"))

            j += 1
        j = 0

        i += 1

    turns -= 1

print(matrix)
###编辑###########我解决了问题

def generator(x,y):

x = int(raw_input("Enter array length"))

y = int(raw_input("Enter array width"))

print(generator(x, y))

return 0

def main():

Total: <span id="totalPrice">£154.67</span>
<br>

<form>

<input id="DebitCard" type="radio" name="payment" checked>
<label for="DebitCard">Debit Card</label>
<br>

<input id="CreditCard" type="radio" name="payment">
<label for="CreditCard">Credit Card (2% extra)</label>
<br>

</form>

main()的

1 个答案:

答案 0 :(得分:0)

如果您尝试以下代码段:

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将为您提供最后一项,这就是您想要的。