2015-11-05 125 views
1

我在当前的python脚本中有许多海龟。它们被命名为T1,T2,T3,T4 ......我有很多的设置来为每个乌龟做的,所以不是类型通过变量列表循环循环的python

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 i in range(0,3): 
    x.speed(0) 
    x.hideturtle() 

因此,这将通过4次循环,在X上移动到下一个变量每次通过。这是我至少希望它做到的。我不是最好的循环,我已经看过所有相关的线程和指南,但我似乎无法弄清楚。

此外,我应该用

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

让所有我需要做的就是添加一个新的龟到列表中,而不必改变循环的量通过在每个for循环?我希望这是有道理的,请评论,如果没有,我会编辑尽我所能。

回答

4

把你的变量列表,而不是字符串文字:

x = [t1, t2, t3, t4] 

然后,你可以这样做:

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

或者干脆:

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

您可能还需要看看使用class

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种海龟,所有实例化无论你的基地“设置”是:

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

当然,它应该不用说,一旦你有定义你的类turtle对象,你现在可以编写代码,根据你可能需要的任何条件动态添加海龟。

+1

的世界x中的turle比使用该范围更加pythonic。 – gipsy

+1

是的@gipsy修改为包括,我原来是从OP的语法工作。 –

1

这听起来像你正在寻找的是这样的:

x = [t1, t2, t3, t4] 

for t in x: 
    t.speed(0) 
    t.hideturtle() 

x是所有海龟的列表。当您执行for t in x时,它将循环显示您的列表并将t指定为当前乌龟,然后设置其速度并隐藏它。这样就没有必要使用range(len(x))

0

,你可以这样做:

x = [t1, t2, t3, t4] 
for item in x: 
    item.speed(0) 
    item.hideturtle() 

x = [t1, t2, t3, t4] 
for i in xrange(len(x)): 
    x[i].speed(0) # you should change the element in x, rather use x 
    x[i].hideturtle() 
0

而不是增加你的龟到列表中的字符串表示加龟对象本身。

例如

turtles = [t1, t2, t3, t4] # t1, t2, t3, and t4 are turtle objects 

然后遍历海龟,并调用你的方法:

for turtle in turtles: 
    turtle.speed(0) 
    turtle.hideturtle() 
0
turtles = [t1, t2, t3, t4] 

# explicitly 
for t in turtles: 
    t.speed(0) 

# wrapped up a bit more 
def turtle_do(fn): 
    for t in turtles: 
     fn(t) 
turtle_do(lambda t: t.hideturtle()) 
0

还是要多简洁,探索lambda表达式

turtles = [t1, t2, t3, t4] 
map(lambda x: x.speed(0), turtles) 
map(lambda x: x.hideTurtle(), turtles) 
+0

简短但带有副作用的地图很难看IMO – user2398029

+0

我还没有遇到任何问题。你能让我意识到吗? user2398029。 –

+0

地图来自函数式编程。 Map是一个将域D映射到范围R的函数的操作。在这里,您正在使用它来修改传递给map(海龟实例)的变量,这并不真正习惯。 – user2398029