【问题标题】:Skip single loop跳过单循环
【发布时间】:2012-08-09 04:27:29
【问题描述】:

我正在遍历文件中的所有行,根据空格将每一行拆分为标记。例如,一行:circle 1 2 3 将被拆分为 4 个标记,circle123

如果该行以注释 (#) 开头或为空,我的 tokenList 也是空的。如果是这种情况,我无法检查tokenList[0]等。

如果列表大小为0,我想跳到下一行——for循环中的下一个循环:


       for line in self.myFile:
            tokenList = self.getTokens(line)
            if len(tokenList) == 0:
                ## ISSUE HERE
            if tokenList[0] == "shape":
                s = RayTracerShapes.Shape()
                self.scene.addShape(s)

我尝试了break,但这似乎直接跳出了循环,而不是结束当前的迭代。有没有办法跳出我所在的循环并进入下一个循环,而无需完全跳出 for 循环?

【问题讨论】:

  • 顺便说一下,您不需要循环以按空格分割。 str.split() 可以为您做到这一点。
  • @acattle getTokens(line) 方法在空格上拆分,并使用str.split() 方法进行一些检查(标记的语法解析以确保合法标记)。不过,感谢您的提示。

标签: python


【解决方案1】:

使用continue 关键字。

当遇到continue 时,将跳过循环体中的其余语句并从循环顶部继续执行。

这个 SO 问题可能会有所帮助:Example use of "continue" statement in Python? 和这个 quick reference 有两个简短的使用示例。

在你的情况下:

   for line in self.myFile:
        tokenList = self.getTokens(line)
        if len(tokenList) == 0:
            continue # skip the rest of the loop, go back to top
        if tokenList[0] == "shape":
            s = RayTracerShapes.Shape()
            self.scene.addShape(s)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多