0

这是我的代码:

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
4

4 回答 4

9

You're missing closing parentheses on every line that calls pieces.append.

于 2012-04-20T19:07:52.847 回答
5
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]
于 2012-04-20T19:13:55.573 回答
1

As others have said, you are missing closing brackets, but that has been said, there is more needed to be done on your code structure:

This is a really bad way of doing what you want to do. A much better solution is to use a dict:

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

Now, this does rely on all your classes taking the same arguments - and while they don't appear to, this (given the errors already in your code) could be a mistake. If it's not, you could separate out that case, and use the mapping for the other cases.

于 2012-04-20T19:09:46.047 回答
1

另一个直接的改进是:

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 模块进行测量。

于 2012-04-20T20:54:56.760 回答