2012-04-20 47 views
0

這裏是我的代碼:的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 

回答

9

你錯過每一個調用pieces.append行右括號。

1

正如其他人所說,你缺少右括號,但已經說了,有更多的需要在您的代碼結構完成的:

這是你想要做什麼做的一個非常糟糕的方式。一個更好的解決方案是使用一個dict

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

現在,這也依賴於所有的類以相同的參數 - 而他們似乎不,這(給你的代碼已經是錯誤)可能是一個錯誤。如果不是,你可以分開的情況,並使用其他情況下的映射。

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

我想休博思韋爾的將是最快的,但是......

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

和使用timeit模塊的措施。