企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 3.3. Tuple 介绍 Tuple 是不可变的 list。一旦创建了一个 tuple,就不能以任何方式改变它。 ## 例 3.15. 定义 tuple ``` >>> t = ("a", "b", "mpilgrim", "z", "example") >>> t ('a', 'b', 'mpilgrim', 'z', 'example') >>> t[0] 'a' >>> t[-1] 'example' >>> t[1:3] ('b', 'mpilgrim') ``` | | | | --- | --- | | \[1\] | 定义 tuple 与定义 list 的方式相同,但整个元素集是用小括号包围的,而不是方括号。 | | \[2\] | Tuple 的元素与 list 一样按定义的次序进行排序。Tuples 的索引与 list 一样从 0 开始,所以一个非空 tuple 的第一个元素总是 `t[0]`。 | | \[3\] | 负数索引与 list 一样从 tuple 的尾部开始计数。 | | \[4\] | 与 list 一样分片 (slice) 也可以使用。注意当分割一个 list 时,会得到一个新的 list ;当分割一个 tuple 时,会得到一个新的 tuple。 | ## 例 3.16. Tuple 没有方法 ``` >>> t ('a', 'b', 'mpilgrim', 'z', 'example') >>> t.append("new") Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> t.remove("z") Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'remove' >>> t.index("example") Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'index' >>> "z" in t 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](index.html#odbchelper.dictionarytypes "例 3.4. 在 dictionary 中混用数据类型") 可以是字符串,整数和 “其它几种类型”吗?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。 ## 进一步阅读 * _How to Think Like a Computer Scientist_ 讲解了 tuple 并且展示了如何[连接 tuple](http://www.ibiblio.org/obp/thinkCSpy/chap10.htm)。 * Python Knowledge Base 展示了如何对[一个 tuple 排序](http://www.faqts.com/knowledge-base/view.phtml/aid/4553/fid/587)。 * _Python Tutorial_ 展示了如何[定义一个只包含一个元素的 tuple](http://www.python.org/doc/current/tut/node7.html#SECTION007300000000000000000)。