Python索引器:列表索引超出范围-2d列表迭代
尝试在Python中遍历以下2d列表,以找到海龟图形的x,y坐标Python索引器:列表索引超出范围-2d列表迭代,python,list,iteration,turtle-graphics,Python,List,Iteration,Turtle Graphics,尝试在Python中遍历以下2d列表,以找到海龟图形的x,y坐标 data_set_01 = [['A', 1, 0, 'N'], ['A', 2, 1, 'E'], ['A', 3, 2, 'S'], ['A', 4, 3, 'W']] 具有以下代码: def draw_icons(data_set): for xpos in data_set: #find x co-ordinates if data_set[[xpos][1]] == 0: xpos = -450
data_set_01 = [['A', 1, 0, 'N'], ['A', 2, 1, 'E'], ['A', 3, 2, 'S'], ['A', 4, 3, 'W']]
具有以下代码:
def draw_icons(data_set):
for xpos in data_set: #find x co-ordinates
if data_set[[xpos][1]] == 0:
xpos = -450
elif data_set[[0][1]] == 1:
xpos = -300
elif data_set[[xpos][1]] == 2:
xpos = -150
elif data_set[[xpos][1]] == 3:
xpos = 0
elif data_set[[xpos][1]] == 4:
xpos = 150
elif data_set[[xpos][1]] == 5:
xpos = 300
for ypos in data_set: #find y co-ordinates
if data_set[[ypos][2]] == 0:
ypos = -300
elif data_set[[ypos][2]] == 1:
ypos = -150
elif data_set[[ypos][2]] == 2:
ypos = 0
elif data_set[[ypos][2]] == 3:
ypos = 150
goto(xpos,ypos)
pendown()
setheading(90)
commonwealth_logo()
获取以下错误:
if data_set[[xpos][1]] == 0:
IndexError: list index out of range
不确定我在这里做错了什么。编辑: 另外,似乎
xpos
实际上是数据集中的完整元素,因为您在数据集中为xpos做了-:
,如果您可以这样做-
xpos[1] #instead of `data_set[[xpos][1]]` .
其他地方也一样
你似乎在错误地为列表编制索引。当你这样做的时候-
data_set[[xpos][1]]
实际上,您正在创建单个元素的列表xpo
,然后从中访问其第二个元素(索引-1),它总是会出错
这不是在Python中索引2D列表的方式。你需要像这样访问-
list2d[xindex][yindex]
让我们一起提取
xpos
和ypos
,并计算位置:
data_set_01 = [['A', 1, 0, 'N'], ['A', 2, 1, 'E'], ['A', 3, 2, 'S'], ['A', 4, 3, 'W']]
def draw_icons(data_set):
for _, xpos, ypos, letter in data_set:
x = (xpos - 3) * 150
y = (ypos - 2) * 150
goto(x, y)
pendown()
setheading(90)
write(letter, align='center') # just for testing
draw_icons(data_set_01)
最好学会使用调试器。例如,你想做什么?data_set_01不是data_set,所以你不共享代码,我愿意打赌你不调试。如果没有足够的上下文,“为什么这段代码不起作用”的问题是无用的,在你没有研究错误并首先调试代码的情况下,永远不应该问这个问题。道歉-这是一个新问题。感谢您的反馈。