为什么我的文件代码有错误?

Why do I have an error on my code with my files?

因此文件 mystery.txt 的行包含单词 UP 或 DOWN 或一对数字。 UP 和 DOWN 是乌龟抬起或放下笔的指令。这对数字是一些 x,y 坐标。 mystery.txt的前几行是

UP
-218 185
DOWN
-240 189
-246 188
-248 183

错误出现在我的 else 语句中:

sammy.goto(wordList[i],wordList[i+1])

我想知道为什么我不应该在这种特殊情况下使用 [i+1] 以及如何解决它。下面是我的代码...

import turtle
turtle.setup(800,600) # Change the width of the drawing to 800px and the height to 600px.
wn = turtle.Screen()
sammy = turtle.Turtle()

inFile = open('mystery.txt','r')
fileString = inFile.read()   # read entire file into a string
inFile.close()   # we're done with the file, so we can close it now
wordList = fileString.split()

for i in range(len(wordList)):
    if str(wordList[i]) == "UP":
        sammy.penup()

    elif wordList[i] == "DOWN":
        sammy.pendown()

    else:
        sammy.goto(wordList[i],wordList[i+1])
        i += 1

错误出现在代码的第 15 行,就在 else 语句之后。错误状态:

IndexError: list index out of range on line 15

这是一种更简洁的方法。

我们逐行遍历文件中的每一行,当我们读到它的时候对待每一行。

当我们有一行坐标时,我们将其拆分并将值转换为 int。

import turtle
turtle.setup(800,600) # Change the width of the drawing to 800px and the height to 600px.
wn = turtle.Screen()
sammy = turtle.Turtle()

with open('mystery.txt','r') as inFile:  # using with will take care of closing the file, whatever happens 
    for line in inFile:  # read and treat the file line by line
        line = line.strip()  # remove the trailing '\n'

        if line == "UP":
            sammy.penup()

        elif line == "DOWN":
            sammy.pendown()

        else:
            # we have a pair of coordinates, we split the line and convert the coords to int
            x, y = map(int, line.split())
            sammy.goto(x, y)

请注意,在 Python 中迭代时,大多数情况下您不需要使用索引,这避免了您遇到的那种问题。

我认为这里真正的问题是您对 i += 1 在此代码中的作用有误解:

for i in range(len(wordList)):
    # ...
    else:
        # ...
        i += 1

C 等语言不同,在 for 循环中,您无法影响下一次迭代的变量 i 的值。如果 i 在下一次迭代中会是 4,那么在本次迭代结束时 i += 1 不会改变它。无论您在 for 循环体中对 i 做什么,都不会影响下一次迭代。但是,在这种情况下我们可以使用 while 代替:

import turtle

turtle.setup(800, 600)

inFile = open('mystery.txt')
fileString = inFile.read()
inFile.close()

wordList = fileString.split()

while wordList:
    if wordList[0] == "UP":
        turtle.penup()
    elif wordList[0] == "DOWN":
        turtle.pendown()
    else:
        turtle.goto(int(wordList[0]), int(wordList[1]))
        wordList.pop(0)

    wordList.pop(0)

turtle.exitonclick()

尽管我实际上会像@ThierryLathuille 建议的那样逐行执行:

from turtle import Screen, Turtle

COMMAND_FILE = 'mystery.txt'

COMMANDS = {'UP': Turtle.penup, 'DOWN': Turtle.pendown}

screen = Screen()
screen.setup(800, 600)

turtle = Turtle()

with open(COMMAND_FILE) as inFile:
    for line in inFile:
        line = line.strip()

        if line in COMMANDS:
            COMMANDS[line](turtle)
        else:
            turtle.goto(map(int, line.split()))

screen.exitonclick()