- Python编程基础与应用
- 李方园主编
- 587字
- 2025-02-24 17:50:26
2.3.2 元组的基本操作与方法
1.通用操作
作为序列的一员,元组可使用“+”和“*”等操作符,其中“+”用于组合元组,“*”用于重复元组。对元组操作的函数基本是可以参照表2-1所示的函数,有len()、in()等。
【例2-28】 元组操作符、函数在表达式或语句中的使用。

运算结果:

2.访问元组元素
和列表一样,可以使用索引(index)访问元组中的某个元素(得到的是一个元素的值),也可以使用切片访问元组中的一组元素(得到的是一个新的子元组)。
使用索引访问元组元素的格式为:

其中,tuplename表示元组名字,i表示索引值。元组的索引可以是正数,也可以是负数。
使用切片访问元组元素的格式为:

其中,start表示起始索引,end表示结束索引,step表示步长。
【例2-29】 访问元组中的某个元素或某组元素。


运算结果:

3.修改元组
元组是不可变序列,其中的元素不能修改,如果要修改,只能给元组重新赋值,替代旧的元组。
【例2-30】 对元组变量进行重新赋值。

运算结果:

【例2-31】 连接多个元组(使用“+”)。

运算结果:

4.删除元组
当创建的元组不再使用时,可以用del关键字将其删除。
【例2-32】 删除元组。

运算结果:

Python自带垃圾回收功能,会自动销毁不用的元组,所以一般不需要通过del来手动删除。
5.其他操作与方法
除了以上操作与方法外,Python元组还包含了以下内置函数。
1)cmp(tuple1, tuple2):比较两个元组元素。
2)len(tuple):计算元组元素个数。
3)max(tuple):返回元组中元素最大值。
4)min(tuple):返回元组中元素最小值。
5)tuple(seq):将列表转换为元组。