用海龟画三角形

Draw Triangle by turtle

我是python的初学者,找到了一个用Turtle绘制三角形的代码,如下代码

def drawPolygon(t, vertices):
    t.up()
    (x, y) = vertices[-1]
    t.goto(x, y)
    t.down()
    for (x, y) in vertices:
        t.goto(x, y)

import turtle
t = turtle.Turtle()
t.hideturtle()
drawPolygon(t, [(20, 20), (-20, 20), (-20, -20)])

turtle.done()

我不明白的第一件事是:(x, y) = vertices[-1]

我不明白的第二件事是:for (x, y) in vertices:

在您的代码中,vertices 是传递给函数的列表,因此 (x, y) = vertices[-1]只需访问列表中的最后一个元素(-1 表示从末尾开始),(x,y) 是一个元组来存储返回的值。 for (x, y) in vertices: 只是一种遍历列表顶点中所有元素的方法。

更多信息请参考这些:

https://docs.python.org/3/tutorial/controlflow.html

https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

第一行:(x, y) = vertices[-1]基本上是在说

Take the last element in list vertices, which is (-20, -20), and assigned its elements to x and y.

所以x等于-20,y也等于-20。

第二行:for (x, y) in vertices:。该行创建了一个 for loop.

这个特定的循环遍历列表 vertices,并获取每个值,并使乌龟使用 .goto() 函数转到该值。

希望对您有所帮助!

(x, y) = vertices[-1]

-1的订阅是指获取数组的最后一个元素,本例为(-20, -20)


for (x, y) in vertices:

将使python遍历数组中的每个元素,在每次迭代期间,可以通过调用(x, y).

访问迭代的元素