简体   繁体   中英

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

Trying to iterate through the following 2d list in Python to find an x,y co-ordinate for turtle graphics.

data_set_01 = [['A', 1, 0, 'N'], ['A', 2, 1, 'E'], ['A', 3, 2, 'S'], ['A', 4, 3, 'W']]

Have the following code:

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()

Get the following error:

if data_set[[xpos][1]] == 0:
IndexError: list index out of range

Not sure what I'm doing wrong here.

EDIT :

Also , seems like xpos is actually the complete element in your data_set since you do - for xpos in data_set: , if you so can simply do the -

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

Similarly at all other places.


You seem to be indexing your lists wrongly . When you do -

data_set[[xpos][1]]

You are actually creating a list of single element xpos and then accessing its 2nd element (index - 1) from it, it would always error out.

This is not how you index 2D list in Python. You need to access like -

list2d[xindex][yindex]

Let's extract xpos & ypos together and calculate the position:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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