天天看點

python文檔:清單

3.1.3. 清單 Python  中可以通過組合一些值得到多種 複合 資料類型。其中最常用的 清單 ,可以通過方括号括起、逗号分隔的一組值(元素)得到。一個 清單 可以包含不同類型的元素,但通常使用時各個元素類型相同:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]      

和字元串(以及各種内置的 sequence 類型)一樣,清單也支援索引和切片:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]      

所有的切片操作都傳回一個包含所請求元素的新清單。 這意味着以下切片操作會傳回清單的一個 淺拷貝:

>>> squares[:]
[1, 4, 9, 16, 25]      

清單同樣支援拼接操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]      

與 immutable 的字元串不同, 清單是一個 mutable 類型,就是說,它自己的内容可以改變:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]      

你也可以在清單末尾通過 append() 方法 來添加新元素(我們将在後面介紹有關方法的詳情):

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]      

給切片指派也是可以的,這樣甚至可以改變清單大小,或者把清單整個清空:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]      

内置函數 len() 也可以作用到清單上:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4      

也可以嵌套清單 (建立包含其他清單的清單), 比如說:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'