2015-08-28 113 views
-4

尝试遍历Python中的以下2d列表以查找x,y坐标为龟图形。Python IndexError:列表索引超出范围 - 2d列表迭代

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 

不知道我做错了这里。

+0

最好学会使用调试器。例如参见['pdb'](https://docs.python.org/2/library/pdb.html)。 – juanchopanza

+0

你想做什么? – Cyphase

+0

data_set_01不是data_set,所以你不用共享代码,我愿意打赌你没有调试。 “为什么这个代码没有工作”的问题没有足够的上下文是没有用的,如果没有你研究这个错误并首先调试你的代码,永远不应该被问到。 –

回答

0

编辑:

而且,好像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] 
0

让我们提取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) 
相关问题