元组(Tuple)

定义
元组和列表很像,包括索引查询、查找统计元素操作都很类似。但是元素是不可变的,无法改变元素,所以没有增删改操作

初始化元组

元组是不可变的,所以初始化元组内的元素不可改变

>>> t = tuple()    # 初始化一个空元组
>>> t = ()    # 也是初始化一个空元组
>>> t = (1)    # 初始化一个元素的元组
>>> t = (1, 2, 3)     # 初始化三个元素的元组

下标/索引查询

元组中的索引是从前往后,索引也是从0开始。从后往前,索引是从-1开始
如果索引超出范围,将引发IndexError异常
元组中,是无法更改元素的值的,更改会抛出TypeError的异常

示例

>>> t = (1, 2, 3)
>>> t[0]    # 索引0的值
1
>>> t[-1]    # 索引-1的值
3
>>> t[3]    # 索引3,超出范围报错
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-81-7d5cf04057c5> in <module>()
----> 1 t[3]

IndexError: tuple index out of range

>>> t[2] = 5    # 元组无法更改索引的值,错误TypeError
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-99b58937a316> in <module>()
----> 1 t[2] = 5

TypeError: 'tuple' object does not support item assignment

查找/统计元素

index

查找某值的第一个索引,可以指定索引的开始和结束位置(包含start,不包含stop),如果值没有找到抛出ValueError

示例

>>> t = tuple('abcdb')
>>> t
('a', 'b', 'c', 'd', 'b')
>>> t.index('b')    # 查找第一次出现值为'b'的索引的位置
1
>>> t.index('b', 2)    # 从索引2开始,查找第一次出现值为'b'的索引的位置
4
>>> t.index('x')    # 没找到'x'
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-88-f70009aaced2> in <module>()
----> 1 t.index('x')

ValueError: tuple.index(x): x not in tuple

>>> t.index('b', 2, 4)    # 'b'没在2-4索引范围内出现
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-89-b86686f7c5fa> in <module>()
----> 1 t.index('b', 2, 4)

ValueError: tuple.index(x): x not in tuple

count

计数、返回值出现的次数

示例

>>> t
('a', 'b', 'c', 'd', 'b')
>>> t.count('b')
2

len

len函数可以用在列表、元组、字符串、集合等上面,输出容器中元素的个数
示例

>>> t
('a', 'b', 'c', 'd', 'b')
>>> len(t)
5
posted @ 2020-11-23 21:52  一墨无辰  阅读(568)  评论(0)    收藏  举报