[英]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."
我不认为这是字典的问题,因为它说“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.您调用
findCoordsFromGrid
两次。 The first time you call it, it finds the 2
and returns its coordinates.第一次调用它时,它会找到
2
并返回它的坐标。 But you also replace 2
with 69420
, so 2 isn't in the grid anymore.但是您也将
2
替换为69420
,因此 2不再在网格中。 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]
. IndexError
来自表达式findCoordsFromGrid(2)[0][1]
,相当于[][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]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.