0

我有一个海龟方向列表:

redlist = ['seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)']

如何使用列表填写此内容?

4

2 回答 2

0

尽管像这样的语法正确的 Python 语句列表似乎是一个使用的机会eval(),但请抵制这种诱惑。这里的语法很简单,函数只有一个参数,我们可以使用re模块来解析命令,并且只针对有效参数执行看似有效的函数:

import turtle
import re

redist = [ \
    'seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', \
    'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', \
    'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', \
    'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)' \
    ]

valid_functions = { \
    'seth': turtle.setheading, \
    'forward': turtle.forward, \
    }

valid_arguments = { \
    'drawdist': 50, \
    }

turtle.begin_fill()

for command in redist:
    match = re.match(r"^(\w+)\((\w+)\)$", command)

    if match is None:
        raise SyntaxError("Invalid syntax")

    function, argument = match.group(1), match.group(2)

    if function not in valid_functions:
        raise ValueError("Invalid function")

    if argument in valid_arguments:
        argument = valid_arguments[argument]
    elif argument.isdigit():
        argument = int(argument)
    else:
        raise TypeError("Invalid argument")

    valid_functions[function](argument)

turtle.end_fill()

turtle.hideturtle()

turtle.mainloop()

对于那些想提前阅读的人,它会画一个实心正方形。我在上面提出的异常可能不是正确的,但重点是在尝试执行作为字符串传递给您的代码时,您需要对所有内容进行错误检查并引发异常。

于 2016-12-05T07:09:30.063 回答
-1

使用pendown, 然后fillcolor循环中的方法:

def draw_n_fill(self,redlist):
  self.pendown()
  [self.getAttr(entry)() for entry in redlist] 
  self.fillcolor("red")

参考

于 2013-10-11T22:02:50.140 回答