【问题标题】:Use a for loop to create a set of turtles from a list in Python使用 for 循环从 Python 中的列表创建一组海龟
【发布时间】:2018-07-10 02:29:06
【问题描述】:

我正在尝试在 Python 中创建海龟列表。我可以通过以下方式手动实现:

import turtle
wn = turtle.Screen()

one = turtle.Turtle()
two = turtle.Turtle()

我希望使用以下 for 循环遍历海龟名称列表,但语法让我很困惑:

import turtle
wn = turtle.Screen()

for turtleName in ["one","two"]:
    turtleName = turtle.Turtle()

one.left(60)
one.forward(160)

NameError: name 'one' is not defined

【问题讨论】:

  • 不要这样做。使用dict

标签: python list for-loop turtle-graphics


【解决方案1】:

当你这样做时

for turtleName in ["one","two"]:
    turtleName = turtle.Turtle()

您正在此循环中创建一个变量,并且对于列表中的每个值,它都会获取其值。

例如,在第一次迭代中,turtleName 中的值将为“one”,而在第二次迭代中,它将为“two”。

当你这样做时

turtleName = turtle.Turtle()

您正在覆盖循环给定的 turtleName 值。

你想要的是动态创建变量,我不知道是否可以,但是你可以使用dict来做一些接近你想要的事情,例如,你可以尝试

names = ['one', 'two']
turtle_dict = dict()

for name in names:
   turtle_dict[name] = turtle.Turtle()

所以当你想用它的名字来称呼乌龟时,你可以这样做

turtle_dict['one'].left(60)

turtle_dict['two'].left(60)

有关 dict 如何工作的更多信息,您可以查看official documentation

我希望这会有所帮助:)

【讨论】:

  • 这很有意义。感谢您的帮助!
【解决方案2】:

你想做什么

for turtleName in ["one","two"]:
    turtleName = turtle.Turtle()

正在为变量turtleName 赋值“一”。 就像 juanpa.arrivillaga 所说的那样,使用字典。

import turtle
wn = turtle.Screen()
dict = {}
for turtleName in ["one","two"]:
    dict[turtleName] = turtle.Turtle()

dict["one"].left(60)
dict["two"].forward(160)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2023-03-29
    • 2018-09-14
    • 2015-06-23
    相关资源
    最近更新 更多