python学习笔记:五

来源:互联网 发布:java事务的四个特性 编辑:程序博客网 时间:2024/06/18 00:05
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。 
原创粉丝点击