![](/img/trans.png)
[英]Why am I getting an IndexError in Python 3 when indexing a string and not slicing?
[英]Why am I getting a IndexError when I'm indexing a list?
我正在创建一个游戏,我试图将数组中的特定值转换为数组的坐标,然后转换为窗口中的像素值。 这是整个脚本的一部分,它有同样的问题。 我不认为这是字典的问题,因为它说“IndexError:list index out of range”。 我已经在这个程序上呆了几个小时了,我想我在这里遗漏了一些简单的东西,所以如果有人能用一双新的眼睛来看看它会很棒。 先感谢您!
这是代码:
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]]]
您调用findCoordsFromGrid
两次。 第一次调用它时,它会找到2
并返回它的坐标。 但是您也将2
替换为69420
,因此 2不再在网格中。 结果,第二次调用它时,它返回一个空列表。 IndexError
来自表达式findCoordsFromGrid(2)[0][1]
,相当于[][0][1]
。
只需保存返回值,而不是两次调用该函数。 (或者不要修改网格;我不确定你为什么要这样做。)
coords = findCoordFromGrid(2)
head_pixelValues = [gridDict[coords[0][0]], gridDict[coords[0][1]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.