2012-03-25 145 views
0

您好,新來的python在一本書中發現了這段代碼,想試試它,但是第4行說它出現一個錯誤「遇到以下類型之一時遇到了以下內容和括號列表。類型聲明python錯誤

#: arrays/PythonLists.py 

aList = [1, 2, 3, 4, 5] 
print type(aList) # <type 'list'> 
print aList # [1, 2, 3, 4, 5] 
print aList[4] # 5 Basic list indexing 
aList.append(6) # lists can be resized 
aList += [7, 8] # Add a list to a list 
print aList # [1, 2, 3, 4, 5, 6, 7, 8] 
aSlice = aList[2:4] 
print aSlice # [3, 4] 


class MyList(list): # Inherit from list 
    # Define a method, 'this' pointer is explicit: 
    def getReversed(self): 
     reversed = self[:] # Copy list using slices 
     reversed.reverse() # Built-in list method 
     return reversed 

list2 = MyList(aList) # No 'new' needed for object creation 
print type(list2) # <class '__main__.MyList'> 
print list2.getReversed() # [8, 7, 6, 5, 4, 3, 2, 1] 

#:~ 
+0

應該工作。有什麼問題? – 2012-03-25 21:43:12

+0

適合我,你確定這正是你想要執行的嗎? – 2012-03-25 21:47:39

+0

您確定此代碼無效嗎?我只是複製粘貼並試用了它,它工作得很好。 – gefei 2012-03-25 21:47:57

回答

4

您正在使用Python 3.x中,其中print是一個函數,不再是一個聲明。這本書是爲Python 2.x中,其中印刷仍然是一個語句寫的。

你解決它通過使用與本書描述相匹配的Python版本,或者獲得新版Python(3.x)的書籍

您的直接的問題可以通過編寫來解決

print (type(aList)) 
+0

只有我能看到的東西。 Python 2.x解釋器與所提供的代碼一起使用。 – Makoto 2012-03-25 21:58:28