Python序列——元组

1. 元组是什么

元组也是序列的一种,元组与列表非常相近,元组是一种不可变类型。

1.1 创建元组

>>> t = tuple()
>>> type(t)
<type 'tuple'>
>>> t1 = ()
>>> t1
()
>>> type(t1)
<type 'tuple'>
>>> t = (1)
>>> type(t)
<type 'int'>
>>> t = (1,)
>>> type(t)
<type 'tuple'>

1.2 访问元组中的值

与列表类似,如:

>>> t = tuple('furzoom')
>>> print t
('f', 'u', 'r', 'z', 'o', 'o', 'm')
>>> t[1]
'u'
>>> t[1:3]
('u', 'r')

1.3 更新元组中的元素

由于元组是不可变类型,所以不支持直接修改元组中的元素,可以通过类型对字符串的操作实现,将元组切片,然后组合,如:

>>> t = tuple('furzoom')
>>> t[1] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t = t[:4] + tuple('uu') + t[-1:]
>>> t
('f', 'u', 'r', 'z', 'u', 'u', 'm')

1.4 删除元组中的元素或者元组本身

>>> t = tuple('furzoom')
>>> t = t[:4] + t[-1:]
>>> t
('f', 'u', 'r', 'z', 'm')
>>> del t
>>> t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined

2. 元组相关操作

支持比较运算、切片[]或者[:]、in, not in、连接操作符+、重复操作。

3. 内建函数对元组的支持

3.1 序列类型函数

支持序列的内建函数。

  • cmp()
  • len()
  • max()
  • min()
  • sorted()
  • reversed()
  • enumerate()
  • zip()
  • sum()
  • list()
  • tuple()

其中,cmp()函数比较的原则与对list的比较是一致的,详见Python序列——列表

3.2 元组内建函数

由于元组是不可变类型,其支持的操作比列表少了许多。

  • tuple.count(x)
  • tuple.index(x[, start[, end]])
>>> t = tuple('furzoom')
>>> t.count('o')
2
>>> t.index('o')
4

4. 元组的特殊性

从应用层面来讲,不可变类型意味着什么?在2个标准不可变类型里面——数字、字符串、元组——元组是受影响最大的。

由于元组是一种容器,有时只是想改变其中的某个元素,但这是不可以的。

利用元组的的不可变性,把数据传递给一个不了解的API时,可以确保数据不会被修改。要操作从函数返回的元组时,可能通过将其转换为列表进行操作。

元组由于不可变,可以做为字典的关键字。

posted @ 2017-10-22 15:50  枫竹梦  阅读(158)  评论(0编辑  收藏  举报