Python list
在介紹 Python tuple 時,我使用了類比的方法,將其比做一個袋子,您可以在袋子中存放不同的東西。Python list 與此非常類似,因此,它的功能與袋子的功能也非常類似。但有一點是不同的,即您可以使用方括號創建 list,如清單 1 所示。
清單 1. 在 Python 中創建一個 list
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> type(l)<type 'list'>>>> el = [] # Create an empty list>>> len(el)0>>> sl = [1] # Create a single item list>>> len(sl)1>>> sl = [1,] # Create a single item list, as with a tuple>>> len(sl)1
本例展示如何創建包含從 0 到 9(包括 0 和 9)的簡單 list,以及如何創建一個空列表和一個包含單個條目的列表。如果您還記得的話,創建單個條目的 tuple 還需要在單個條目后面跟一個逗號。這是區分單個條目 tuple 與方法調用的必要條件,這一點將在以后的文章中詳細討論。而對于 list,則是不必要的,盡管也允許使用單個逗號。
與往常一樣,要獲取有關 Python 主題的更多信息,您可以使用內置的幫助解釋器,例如,清單 2 展示了如何開始 list 類的幫助描述。
清單 2. 獲取有關 list 的幫助
>>> help(list)Help on class list in module __builtin__:class list(object) | list() -> new list | list(sequence) -> new list initialized from sequence's items | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | ...
如果仔細觀察清單 2 中對 list 類的描述,您會看到其中提供了兩個不同的構造函數:一個沒有參數,另一個接受一個序列類作為參數。因此,使用構造函數及方括號簡化符號,可以創建 list。這就提供了很大的靈活性,原因是您可以方便地將現有的序列,如 tuple 或 string 轉換為 list,如清單 3 所示。不過,請注意,傳遞的參數必須是序列 —— 并且不只是對象序列 —— 否則將會出現錯誤。對于任何序列類型,您都可以使用 len 方法容易地查找序列中條目的數量。
清單 3. 直接創建 list 對象
>>> l = list()>>> type(l)<type 'list'>>>> len(l)0>>> l[]>>> l = list((0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) # Create a list from a tuple>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> len(l)10>>> l = list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # Create a list from a list>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> len(l)10>>> l = list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # Error: Must pass in a sequenceTraceback (most recent call last): File "<stdin>", line 1, in ?TypeError: list() takes at most 1 argument (10 given)>>> l = list("0123456789") # Create a list from a string>>> l['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']>>> type(l)<type 'list'>>>> len(l)10
新聞熱點
疑難解答