繁体   English   中英

Python IndexError:列表索引超出范围 - 二维列表迭代

[英]Python IndexError: list index out of range - 2d list iteration

尝试在 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
    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实际上是您的 data_set 中的完整元素,因为您这样做 - for xpos in data_set: ,如果您可以简单地执行 -

xpos[1] #instead of `data_set[[xpos][1]]` .

在所有其他地方也是如此。


您似乎错误地索引了您的列表。 当你这样做时——

data_set[[xpos][1]]

您实际上是在创建单个元素xpos的列表,然后从中访问它的第二个元素(索引 - 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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