3.Tuple 介绍
Tuple 是不可变的 list。一旦创建了一个 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
那么使用 tuple 有什么好处呢?
-
Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
-
Tuples 可以在 dictionary 中被用做 key,但
是 list 不行。实际上,事情要比这更复杂。Dictionary key 必须是不可变的。Tuple 本身是不可改变的,但是如果您有一个 list 的 tuple,那就认为是可变的了,用做 dictionary key 就是不安全的。只有字符串、整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key
-
Note: Tuple 到 list 再到 tuple
-
Tuple 可以转换成 list,反之亦然
-
从效果上看,tuple 冻结一个 list,而 list 解冻一个 tuple。