【问题标题】:python for loop cycling through list of variablespython for循环遍历变量列表
【发布时间】:2016-02-05 18:11:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: python list for-loop turtle-graphics


    【解决方案1】:

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

    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 对象,你现在就可以编写可以根据你可能需要的任何条件动态添加海龟的代码。

    【讨论】:

    • for turle in x 比使用范围更 Pythonic。
    • 是的@gipsy 修改为包含这一点,我最初是根据 OP 的语法工作的。
    【解决方案2】:

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

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

    x 是您所有海龟的列表。当您执行for t in x 时,它将遍历您的列表并将t 指定为当前海龟,然后设置其速度并将其隐藏。这样就不用range(len(x))了。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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()
      

      【讨论】:

        【解决方案4】:
        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())
        

        【讨论】:

          【解决方案5】:

          而不是将海龟的字符串表示形式添加到列表中,而是添加海龟对象本身。

          例如

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

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

          for turtle in turtles:
            turtle.speed(0)
            turtle.hideturtle() 
          

          【讨论】:

            【解决方案6】:

            或者更简洁,探索 lambdas 的世界

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

            【讨论】:

            • 简短但有副作用的地图很难看 IMO
            • 我没有遇到过。你能让我知道吗?用户2398029。
            • Map 来自函数式编程。 Map 是一个将域 D 映射到范围 R 的函数的操作。在这里,您使用它来修改传递给 map 的变量(海龟的实例),这并不是真正的惯用语。
            • 有道理。感谢您的知识转移:) user2398029
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-04-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-28
            • 2016-04-14
            • 1970-01-01
            • 2017-11-01
            相关资源
            最近更新 更多