【问题标题】:Python IndexError: list index out of range - 2d list iterationPython IndexError:列表索引超出范围 - 2d 列表迭代
【发布时间】:2015-08-28 06:33:17
【问题描述】:

尝试在 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

不知道我在这里做错了什么。

【问题讨论】:

  • 最好学会使用调试器。例如,请参阅pdb
  • 你想做什么?
  • data_set_01 不是 data_set,所以你不共享代码,我愿意赌钱你不调试。如果没有足够的上下文,“为什么这段代码不能正常工作”的问题是没有用的,如果你没有研究过这个错误并首先调试你的代码,就不应该问这个问题。
  • 道歉 - 新的。感谢您的反馈。

标签: python list iteration turtle-graphics


【解决方案1】:

编辑:

另外,看起来 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]

【讨论】:

    【解决方案2】:

    让我们一起提取xposypos并计算位置:

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 2017-04-05
      • 2012-07-15
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多