您当前位置:首页 > 深入 Python > 内置数据类型 > 元组简介 | << >> | ||||
深入 Python从 Python 新手到专家 |
元组是不可变的列表。元组一旦创建就无法以任何方式更改。
>>> t = ("a", "b", "mpilgrim", "z", "example")>>> t ('a', 'b', 'mpilgrim', 'z', 'example') >>> t[0]
'a' >>> t[-1]
'example' >>> t[1:3]
('b', 'mpilgrim')
>>> 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
那么元组有什么用呢?
![]() |
|
元组可以转换为列表,反之亦然。内置的 tuple 函数接受一个列表并返回具有相同元素的元组,而 list 函数接受一个元组并返回一个列表。实际上,tuple 冻结列表,而 list 解冻元组。 |
<< 列表简介 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
声明变量 >> |