【问题标题】:Python For/If Syntax ErrorPython For/If 语法错误
【发布时间】:2012-05-02 09:14:22
【问题描述】:

这是我的代码:

for i in tuples:
    if i[0] == "U_shape":
        pieces.append(U_shape(i[1], boardLength, i[2])
    if i[0] == "I_shape":
        pieces.append(I_shape(i[1], i[2])
    if i[0] == "L_shape":
        pieces.append(L_shape(i[1], boardLength, i[2])
    if i[0] == "T_shape":
        pieces.append(T_shape(i[1], boardLength, i[2])
    if i[0] == "X_shape":
        pieces.append(X_shape(i[1], boardLength, i[2])

这是错误:

if i[0] == "I_shape":
                    ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: python syntax if-statement for-loop


    【解决方案1】:

    调用pieces.append 的每一行都缺少右括号。

    【讨论】:

      【解决方案2】:
      pieceType = {
          "U_shape": U_shape,
          "I_shape": I_shape,
          "L_shape": L_shape,
          "T_shape": T_shape,
          "X_shape": X_shape
      }
      
      pieces = [pieceType[a](b, boardLength, c) for a,b,c in tuples]
      

      【讨论】:

        【解决方案3】:

        正如其他人所说,您缺少右括号,但已经说过,您的代码结构还需要做更多工作:

        这是做你想做的事的一种非常糟糕的方式。一个更好的解决方案是使用dict:

        mapping = {"U_shape": U_shape, "I_shape": I_shape, ...}
        pieces.append(mapping[i[0]](i[1], boardLength, i[2]))
        

        现在,这确实依赖于您所有的类都采用相同的参数 - 虽然它们似乎没有,但这(鉴于您的代码中已经存在错误)可能是一个错误。如果不是,您可以分离出 那个 案例,并将映射用于其他案例。

        【讨论】:

          【解决方案4】:

          另一个直接的改进是:

          for i in tuples:
              if i[0] == "U_shape":
                  pieces.append(U_shape(i[1], boardLength, i[2]))
              elif i[0] == "I_shape":
                  pieces.append(I_shape(i[1], i[2]))
              elif i[0] == "L_shape":
                  pieces.append(L_shape(i[1], boardLength, i[2]))
              elif i[0] == "T_shape":
                  pieces.append(T_shape(i[1], boardLength, i[2]))
              elif i[0] == "X_shape":
                  pieces.append(X_shape(i[1], boardLength, i[2]))
          

          我猜 Hugh Bothwell 的会是最快的,但是...

          >>> import this
          The Zen of Python, by Tim Peters
          ...
          In the face of ambiguity, refuse the temptation to guess.
          ...
          >>>
          

          并使用 timeit 模块进行测量。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-04-21
            • 2012-08-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-23
            • 2013-09-09
            • 2019-01-07
            相关资源
            最近更新 更多