2015-08-28 218 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) 
相關問題