目录
Python 元组(Tuple)是一种有序、不可变的集合类型,可以存储任意类型的元素。
特性/操作 | 描述 | 示例代码 |
---|---|---|
定义 | 用圆括号()创建 | my_tuple = (1, 2, 3) |
访问元素 | 通过索引访问 | print(my_tuple[0]) |
元组长度 | 使用len()获取长度 | length = len(my_tuple) |
元组遍历 | 使用for循环遍历 | for item in my_tuple: |
print(item) | ||
元组拆包 | 使用*拆包 | a, b, *rest = my_tuple |
修改元组 | 不可修改,但可以连接 | new_tuple = my_tuple + (4, 5) |
创建元组
# 创建空元组
tuple1 = ()
# 创建含有一个元素的元组(注意逗号)
tuple2 = (1,)
# 创建多个元素的元组
tuple3 = (1, 2, 3, "hello", 3.14)
# 创建嵌套元组
tuple4 = (1, (2, 3), ["a", "b"])
# 创建没有括号的元组(元组的元素以逗号分隔)
tuple5 = 1, 2, 3, "hello", 3.14
访问元组元素
tuple3 = (1, 2, 3, "hello", 3.14)
# 通过索引访问元素
print(tuple3[0]) # 输出:1
print(tuple3[3]) # 输出:"hello"
# 通过负索引访问元素
print(tuple3[-1]) # 输出:3.14
print(tuple3[-2]) # 输出:"hello"
# 访问嵌套元组元素
print(tuple4[1][0]) # 输出:2
print(tuple4[2][1]) # 输出:"b"
列表与元组互转
# 元组转换为列表
list_from_tuple = list(tuple3)
print(list_from_tuple) # 输出:[1, 2, 3, 'hello', 3.14]
# 列表转换为元组
tuple_from_list = tuple([1, 2, 3, "hello", 3.14])
print(tuple_from_list) # 输出:(1, 2, 3, 'hello', 3.14)
更新和删除元素
元组是不可变的,因此不能直接更新或删除其中的元素,但可以通过其他方式处理:
tuple3 = (1, 2, 3, "hello", 3.14)
# 重新创建一个新的元组来“更新”元素
new_tuple = tuple3[:2] + (4,) + tuple3[3:]
print(new_tuple) # 输出:(1, 2, 4, 'hello', 3.14)
# 删除整个元组
del tuple3
# print(tuple3) # 会引发 NameError: name 'tuple3' is not defined
# 删除元组 tuple3。一旦元组被删除,再次访问它将引发 NameError,因为 tuple3 不再存在。
元组操作符
# 拼接元组
tuple6 = (1, 2) + (3, 4)
print(tuple6) # 输出:(1, 2, 3, 4)
# 重复元组
tuple7 = (1, 2) * 3
print(tuple7) # 输出:(1, 2, 1, 2, 1, 2)
# 判断元素是否在元组中
print(2 in tuple6) # 输出:True
print(5 not in tuple6) # 输出:True
元组内建函数
tuple8 = (1, 2, 3, 2, 1)
tuple9 = (4, 1, 7, 2, 5)
# 获取元组长度
print(len(tuple8)) # 输出:5
# 获取元组中的最大值
print(max(tuple8)) # 输出:3
print(max(tuple9)) # 输出:7
# 获取元组中的最小值
print(min(tuple8)) # 输出:1
print(min(tuple9)) # 输出:1
元组方法
元组有以下两个内建方法:
- count():计算元组中某个元素的出现次数。
- index():返回某个元素在元组中的索引位置。
tuple9 = (1, 2, 3, 2, 1)
# 统计元素出现次数
print(tuple9.count(2)) # 输出:2
# 查找元素的索引
print(tuple9.index(3)) # 输出:2
列表与元组对比
特性 | 列表 (List) | 元组 (Tuple) |
---|---|---|
可变性 | 可变(可以修改元素、添加、删除) | 不可变(不能修改元素) |
语法 | [] |
() |
方法 | append() , remove() , pop() , extend() 等 |
count() , index() |
适用场景 | 数据需要修改的情况 | 数据不需要修改的情况,作为字典的键或集合的元素 |