简体   繁体   中英

Why am I getting a IndexError when I'm indexing a list?

I'm creating a game and I'm trying to convert a specific value in my array to coordinates of my array and then to a pixel value in the window. This is a bit of the whole script, and it has the same issue. I don't think it's a problem with the dictionary because it says "IndexError: list index out of range." I've been at this program for a couple of hours now and I think I'm missing something simple here, so it would be great if someone could look it over with a fresh set of eyes. Thank you in advance!

Here's the code:

gridDict = {
0: 20,
1: 60,
2: 100,
3: 140,
4: 180,
5: 220,
6: 260,
7: 300,
8: 340,
9: 380,
10: 420,
11: 460,
12: 500,
13: 540,
14: 580,
15: 620,
16: 660
}

grid = []

for row in range(17):
    grid.append([])
    for column in range(17):
        grid[row].append(0)


grid[6][8] = 2


def findCoordsFromGrid(gridValue):
    global grid
    referenceGrid = grid.copy()
    coordsLst = []
    for i in range(17):
        for value in referenceGrid[i]:
            if value == gridValue:
                x = referenceGrid[i].index(gridValue)
                y = i
                coordsLst.append([x, y])
                referenceGrid[y][x] = 69420
    return coordsLst


head_pixelValues = [gridDict[findCoordsFromGrid(2)[0][0]], gridDict[findCoordsFromGrid(2)[0][1]]]

You call findCoordsFromGrid twice. The first time you call it, it finds the 2 and returns its coordinates. But you also replace 2 with 69420 , so 2 isn't in the grid anymore. As a result, the second time you call it, it returns an empty list. The IndexError comes from the expression findCoordsFromGrid(2)[0][1] , which is equivalent to [][0][1] .

Instead of calling the function twice, just save the return value. (Or don't modify the grid; I'm not sure why you are doing that.)

coords = findCoordFromGrid(2)
head_pixelValues = [gridDict[coords[0][0]], gridDict[coords[0][1]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM