的Python /如果语法错误
问题描述:
这里是我的代码:的Python /如果语法错误
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
答
你错过每一个调用pieces.append
行右括号。
答
正如其他人所说,你缺少右括号,但已经说了,有更多的需要在您的代码结构完成的:
这是你想要做什么做的一个非常糟糕的方式。一个更好的解决方案是使用一个dict
:
mapping = {"U_shape": U_shape, "I_shape": I_shape, ...}
pieces.append(mapping[i[0]](i[1], boardLength, i[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]
答
另一种简单的改进是:
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]))
我想休博思韦尔的将是最快的,但是......
>>> import this
The Zen of Python, by Tim Peters
...
In the face of ambiguity, refuse the temptation to guess.
...
>>>
和使用timeit模块的措施。