Python编程入门(第10课):不可变序列-元组
一、课程目标
- 学习Python不可变序列的基本特征;
- 学习以元组为代表的不可变序列的基本操作。
二、什么是元组
元组(tuple)是一种不可变的序列数据类型,用于存储一组有序的元素。与列表(list)不同,元组一旦创建后其内容无法修改。
三、创建元组
1. 使用圆括号()创建元组
这是最常见的方法。通过将元素放在圆括号中并用逗号分隔,可以创建一个元组。
In [ ]:
# 创建一个包含多个元素的元组
my_tuple = (1, 2, 3, 4)
print(my_tuple) # 输出: (1, 2, 3, 4)
# 创建一个空元组
empty_tuple = ()
print(empty_tuple) # 输出: ()
# 创建一个只包含一个元素的元组
single_element_tuple = (5,)
print(single_element_tuple) # 输出: (5,)
注意:
- 如果元组中只有一个元素,必须在元素后面加上逗号(,),否则Python会将其视为普通变量而非元组。
In [5]:
not_a_tuple = (5) # 这是一个整数,不是元组
print(type(not_a_tuple)) # 输出:
is_a_tuple = (5,) # 这是一个元组
print(type(is_a_tuple)) # 输出:
2. 使用tuple()构造函数创建元组
可以通过内置的 tuple() 函数将其他可迭代对象(如列表、字符串等)转换为元组。
In [6]:
# 从列表创建元组
list_to_tuple = tuple([1, 2, 3])
print(list_to_tuple) # 输出: (1, 2, 3)
# 从字符串创建元组
string_to_tuple = tuple("hello")
print(string_to_tuple) # 输出: ('h', 'e', 'l', 'l', 'o')
# 从范围对象创建元组
range_to_tuple = tuple(range(5))
print(range_to_tuple) # 输出: (0, 1, 2, 3, 4)
(1, 2, 3)
('h', 'e', 'l', 'l', 'o')
(0, 1, 2, 3, 4)
四、元组的通用操作
元组也是序列,所以上节课讲到的列表的通用操作在元组中同样适用,包括:
1.元组的访问:使用索引
my_tuple = (10, 20, 30, 40)
print(my_tuple[1], my_tuple[-2]) # 正向索引和反向索引
2.元组的嵌套
nested_tuple = ((1, 2), ('a', 'b'))
print(nested_tuple[0][1], nested_tuple[1][0])
3.元组的切片
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4], my_tuple[:3])
4.获取元组的长度
my_tuple = (10, 20, 30)
print(len(my_tuple))
5.检查元素是否包含在元组中
my_tuple = ('apple', 'banana', 'cherry')
print('banana' in my_tuple, 'orange' in my_tuple)
6.获取元组中最大的元素
my_tuple = (10, 20, 5, 25)
print(max(my_tuple))
7.获取元组中最小的元素
my_tuple = (10, 20, 5, 25)
print(min(my_tuple))
8.对元组所有元素求和
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple))
9.加法+运算:连接两个元组
tuple1 = (1, 2)
tuple2 = (3, 4)
print(tuple1 + tuple2)
10.乘法*运算:重复元组相应次数
my_tuple = ('a', 'b')
print(my_tuple * 3)
以上通用操作不再赘述,可以学习上一节课的视频。
五、元组的操作
(一)查找元素:index()
元组的 index() 方法是一个非常有用的内置方法,用于查找某个特定元素在元组中的索引位置。
如果该元素存在于元组中,index() 方法会返回其首次出现的索引值;如果元素不存在,则会引发 ValueError 异常。
语法
tuple.index(element, start, end)
- 参数说明:
- element(必需):要查找的元素。
- start(可选):指定从元组的哪个索引位置开始查找,默认为从头开始(即索引 0)。
- end(可选):指定查找范围的结束索引(不包括该索引),默认为查找至元组末尾。
- 返回值:
- 返回第一个匹配元素的索引值。
- 如果元素不存在于元组中,则抛出 ValueError 异常。
示例代码
1.基本用法
查找某个元素在元组中的索引位置:
In [7]:
my_tuple = (10, 20, 30, 40, 50)
# 查找元素 30 的索引
index_of_30 = my_tuple.index(30)
print(index_of_30) # 输出: 2
# 查找元素 10 的索引
index_of_10 = my_tuple.index(10)
print(index_of_10) # 输出: 0
2
0
2.查找不存在的元素
如果尝试查找元组中不存在的元素,会抛出 ValueError:
In [8]:
my_tuple = (10, 20, 30)
# 尝试查找不存在的元素 40
try:
index_of_40 = my_tuple.index(40)
except ValueError as e:
print("错误:", e) # 输出: 错误: tuple.index(x): x not in tuple
错误: tuple.index(x): x not in tuple
3.使用可选参数start和end
可以通过 start 和 end 参数限制查找范围:
In [9]:
my_tuple = ('a', 'b', 'c', 'd', 'e', 'f')
# 在索引 2 到 5(不包括 5)之间查找 'd'
index_of_d = my_tuple.index('d', 2, 5)
print(index_of_d) # 输出: 3
# 在索引 4 开始查找 'a'(不存在)
try:
index_of_a = my_tuple.index('a', 4)
except ValueError as e:
print("错误:", e) # 输出: 错误: tuple.index(x): x not in tuple
3
错误: tuple.index(x): x not in tuple
注意事项
- 首次出现的位置: 如果元组中有多个相同的元素,index() 方法只会返回第一个匹配元素的索引。
- my_tuple = (1, 2, 3, 2, 4) print(my_tuple.index(2)) # 输出: 1 (第一次出现的位置)
- 区分数据类型: 元组中的元素是严格区分数据类型的。例如,整数 1 和浮点数 1.0 是不同的元素。
- my_tuple = (1, 1.0, '1') print(my_tuple.index(1)) # 输出: 0 print(my_tuple.index(1.0)) # 输出: 1 print(my_tuple.index('1')) # 输出: 2
- 不可变性的影响: 由于元组是不可变的,因此无法直接修改元组的内容。如果需要根据索引操作数据,通常需要先将元组转换为列表,进行修改后再转回元组。
(二)统计指定值在元组中出现的次数:count()
元组的 count() 方法用来计算某个指定值在元组中出现的次数。如果该值存在于元组中,则返回它的出现次数;如果该值不存在,则返回 0。
In [ ]:
my_tuple = (1, 2, 3, 2, 4, 2)
# 统计数字 2 出现的次数
count_of_2 = my_tuple.count(2)
print(count_of_2) # 输出: 3
# 统计数字 5 出现的次数(不存在)
count_of_5 = my_tuple.count(5)
print(count_of_5) # 输出: 0
(三)元组的排序
元组本身是不可变的数据类型,这意味着一旦创建,元组的内容无法直接修改。因此,元组本身并没有提供类似于列表的 sort() 方法来实现“原地排序”。
使用sorted()函数
sorted() 是一个内置函数,可以对任何可迭代对象(包括元组)进行排序,并返回一个新的列表。原始元组不会被修改。
语法
sorted(iterable, key=None, reverse=False)
- 参数说明:
- iterable:需要排序的可迭代对象(如元组)。
- key(可选):指定排序规则的函数,默认为 None。
- reverse(可选):布尔值,True 表示降序排序,False 表示升序排序(默认)。
- 返回值:
- 返回一个排序后的新列表。
示例代码
In [11]:
my_tuple = (3, 1, 4, 2)
# 升序排序
sorted_list = sorted(my_tuple)
print(sorted_list) # 输出: [1, 2, 3, 4]
# 如果需要将结果转换回元组
sorted_tuple = tuple(sorted_list)
print(sorted_tuple) # 输出: (1, 2, 3, 4)
# 降序排序
sorted_list = sorted(my_tuple, reverse=True)
print(sorted_list) # 输出: [4, 3, 2, 1]
# 转换回元组
sorted_tuple = tuple(sorted_list)
print(sorted_tuple) # 输出: (4, 3, 2, 1)
[1, 2, 3, 4]
(1, 2, 3, 4)
[4, 3, 2, 1]
(4, 3, 2, 1)
易错点总结
- 如果元组中只有一个元素,仍然需要加逗号,否则就不是一个元组;
- 元组为不可变序列,列表中有的如添加元素、更新元素、删除元素等在元组中不适用;
- 使用sorted()进行排序后,返回的是列表,而不是元组。