python學習筆記:五

python 標準類型之Tuple

Tuple (元組)是不可變 list。 一旦創建了一個 tuple 就不能以任何方式改變它。

定義 tuple
>>> t = ("a", "b", "mpilgrim", "z", "example") 1
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t[0]                                       2
'a'
>>> t[-1]                                      3
'example'
>>> t[1:3]                                     4
('b', 'mpilgrim')
1  定義 tuple 與定義 list 的方式相同, 除了整個元素集是用小括號包圍的而不是方括號。 
2  Tuple 的元素與 list 一樣按定義的次序進行排序。 Tuples 的索引與 list 一樣從 0 開始, 所以一個非空 tuple 的第一個元素總是 t[0]。 
3  負數索引與 list 一樣從 tuple 的尾部開始計數。 
4  與 list 一樣分片 (slice) 也可以使用。注意當分割一個 list 時, 會得到一個新的 list ;當分割一個 tuple 時, 會得到一個新的 tuple。 


Tuple 沒有方法
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.append("new")    1
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove("z")      2
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.index("example") 3
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'
>>> "z" in t           4
True
1  您不能向 tuple 增加元素。Tuple 沒有 append 或 extend 方法。 
2  您不能從 tuple 刪除元素。Tuple 沒有 remove 或 pop 方法。 
3  您不能在 tuple 中查找元素。Tuple 沒有 index 方法。 
4  然而, 您可以使用 in 來查看一個元素是否存在於 tuple 中。 


那麼使用 tuple 有什麼好處呢?


Tuple 比 list 操作速度快。如果您定義了一個值的常量集, 並且唯一要用它做的是不斷地遍歷它, 請使用 tuple 代替 list。 
如果對不需要修改的數據進行 “寫保護”, 可以使代碼更安全。使用 tuple 而不是 list 如同擁有一個隱含的 assert 語句, 說明這一數據是常量。如果必須要改變這些值, 則需要執行 tuple 到 list 的轉換 (需要使用一個特殊的函數)。 
還記得我說過 dictionary keys 可以是字符串, 整數和 “其它幾種類型”嗎? Tuples 就是這些類型之一。 Tuples 可以在 dictionary 中被用做 key, 但是 list 不行。實際上, 事情要比這更復雜。Dictionary key 必須是不可變的。Tuple 本身是不可改變的, 但是如果您有一個 list 的 tuple, 那就認爲是可變的了, 用做 dictionary key 就是不安全的。只有字符串, 整數或其它對 dictionary 安全的 tuple 纔可以用作 dictionary key。 
Tuples 可以用在字符串格式化中, 我們會很快看到。 
注意 
Tuple 可以轉換成 list, 反之亦然。內置的 tuple 函數接收一個 list, 並返回一個有着相同元素的 tuple。而 list 函數接收一個 tuple 返回一個 list。從效果上看, tuple 凍結一個 list, 而 list 解凍一個 tuple。 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章