Skip to main content
 首页 » 编程设计

python for循环遍历变量列表

2025年05月04日30zdz8207

我当前的 python 脚本中有很多 turtle 。它们被命名为 t1、t2、t3、t4...我要为每只 turtle 做很多设置,所以不用输入

t1.speed(0) 
t2.speed(0) 
t3.speed(0) 
t4.speed(0) 
 
t1.hideturtle() 
t2.hideturtle() 
t3.hideturtle() 
t4.hideturtle() 

看来我应该可以将它们放入列表中,

x = ["t1", "t2", "t3", "t4"] 

然后有一个for循环做这样的事情

for i in range(0,3): 
    x.speed(0) 
    x.hideturtle() 

所以它会循环 4 次,每次循环都移动到 x 中的下一个变量。至少这是我希望它做的。我不是最擅长 for 循环的,我已经查看了所有相关的线程和指南,但我似乎无法弄清楚。

另外,我应该使用

length = len(x) 
for i in range(length): 
    #stuff 

所以我所要做的就是向列表中添加一个新的 turtle ,而不是必须更改每个 for 循环中的循环次数?我希望这是有道理的,如果没有,请发表评论,我会尽我所能进行编辑。

请您参考如下方法:

将您的变量放在列表中,而不是字符串文字:

x = [t1, t2, t3, t4] 

然后你可以这样做:

for i in range(len(x)): 
  #stuff, like: 
  x[i].hideturtle() 

或者简单地说:

for turtle in x: 
    turtle.hideturtle() 
    # etc. 

您可能还想看看使用类。

https://docs.python.org/2/tutorial/classes.html

class turtle(): 
    """ example of a class representing some sort of turtle """ 
    def __init__(self): 
        # assign the default properties of the class 
        self.speed = 0 
        self.hidden = False 
    def hideturtle(self): 
        self.hidden = True 
    def unhideturtle(self): 
        self.hidden = False 
    def setspeed(self, increment): 
        # increase/decrease the current speed 
        self.speed = 0 if self.speed += increment < 0 else self.speed += increment 
    def stop(self): 
        self.speed = 0 
 
 
x = turtle() 
y = turtle() 
 
x.speed, y.speed = 10, 5 
x.hideturtle() 
print x.speed, y.speed, x.hidden, y.hidden 
 
>>> 10, 5, True, False 

要在一个列表中创建 5 只 turtle ,所有这些都实例化为您的基础“设置”是什么:

turtles = [] 
for i in range(5): 
  turtles.append(turtle()) 

当然,不用说,一旦您定义了类 turtle 对象,您现在就可以编写代码,根据您可能需要的任何条件动态添加 turtle 。