【问题标题】:Python IndexError: list assignment index out of rangePython IndexError:列表分配索引超出范围
【发布时间】:2013-10-18 13:58:46
【问题描述】:

谁能指出我出了什么问题?

我被newGrid.setValue(n[k][0], n[k][1], List[k]) 卡住了,试图将每个坐标的每个 x/y 的值输入到一个不同的函数中,该函数需要三个参数,x y 和 value。值是在网格上某个位置打印的内容,x & y 是坐标。

self.listOfRows[x - 1][y - 1] = value 

IndexError: 列表赋值索引超出范围

def gridMileage(List):
    x = []
    y = []
    n = []
    k = 0
    best = 0
    while len(List) > 0:
        for i in range(len(List)):
            x = List[i][0]
            y = List[i][1]
            n.append([x,y])
        if x > best:
            best = x
        elif y > best:
            best = y
        newGrid = Grid(best)
        while k < 2:
            newGrid.setValue(n[k][0], n[k][1], List[k])
            k = k + 1
        del List[0]
        del List[1]
        del n[0]
        del n[1]
        newGrid.setValue(n[0], n[0] + 1, math.sqrt((n[0][0] - n[1][0])**2 + (n[0][1] - n[1][1])**2))
        newGrid.setValue(n[1] + 1, n[1], math.sqrt((n[1][0] - n[0][0])**2 + (n[1][1] - n[0][1])**2))
        z = len(newGrid.listOfRows)
        while z > 0:
            print(newGrid.listOfRows[z - 1])
            z = z - 1

class Grid:
    def __init__(self, n):
        self.listOfRows = []
        for i in range(n):
            row = []
            for j in range(n):
                row.append('*')
            self.listOfRows.append(row)

    def setValue (self, x, y, value):
        self.listOfRows[x - 1][y - 1] = value

【问题讨论】:

    标签: python


    【解决方案1】:

    问题在于,您最终似乎输入了一个太小或太大的列表索引。

    根据错误信息,有问题的代码是self.listOfRows[x - 1][y - 1] = value。您可以通过 newGrid.setValue(n[k][0], n[k][1], List[k]) 调用它。问题不可能是List[k],因为这不是导致堆栈跟踪的原因。

    因此,这意味着n[k][0] 或n[k][1] 对于newGrid.listOfRows 来说太大了。

    我会通过在该行之前添加打印语句来仔细检查您的代码以检查这两个值,并仔细检查您的网格到底有多大。

    因为您似乎向n 添加任何值的唯一地方是(我认为?):

    for i in range(len(List)):
        x = List[i][0]
        y = List[i][1]
        n.append([x,y])
    

    ...这意味着根本问题在于您传入的 List 变量。

    【讨论】:

    • 谢谢 - 我发现错误出在我确定网格大小时,我使用了 If-Elif,并且网格已将自身初始化为 1*1 - 它没有t 检查 y 坐标是否更大,因此无法将坐标 (2, 3) 传递给网格。
    【解决方案2】:
    self.listOfRows[x - 1][y - 1] = value 
    

    如果 x 和 y 是 0 这给了你

    self.listOfRows[-1][-1] = value 
    

    不存在

    【讨论】:

    • self.listOfRows[x][y] = value IndexError: list index out of range
    • List[i][0] newGrid.setValue(n[k][0], n[k][1], List[k]) 你是把一个数组变成一个值吗?
    猜你喜欢
    • 2018-10-21
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2022-11-27
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多