元组的定义
本质上也是一种有序的集合,元组使用()表示。但与list不同,元组一旦初始化则不能修改。
创建元组
tuple1 =() #创建空元组
tuple2 = tuple() #创建空元组
tuple3 = (1,) #创建只有一个元素的元组
tuple4 = 1, #创建只有一个元素的元组
注意:当元组中只有一个元素的时候,我们必须在该元素的末尾添加一个逗号,来消除歧义。元组小括号可以省略,但是逗号不能省略
tuple1 = (1)
tuple2 = (1,)
tuple3 = 1,2,3,4,5
print(tuple1)
print(tuple2)
print(tuple3)
print(type(tuple1))
print(type(tuple2))
print(type(tuple3))
运行结果如下:
1
(1,)
(1, 2, 3, 4, 5)
<class 'int'>
<class 'tuple'>
<class 'tuple'>
元组元素的访问
1. 访问元组中的元素
tuple1 = (元素1,元素2,…,元素n)
我们可以通过索引值/下标来进行访问,如tuple1[index],其中index的取值范围为[0,len(tuple1))
注意:index取值可以为负,为负的时候,从右往左进行取值
tuple1 = (1,2,3,4,5,True,"hello",[1,2,3])
print(tuple1[5]) #True
print(tuple1[-2]) #hello
2. 修改元组
指的是在元组的内部添加一个可变对象,通过修改可变对象进而来修改我们的元组。在元组中一旦初始化则不能修改指的是,元组一旦创建,它对应元素指向不会再发生变化。
tuple1 = (1,2,3,4,5,True,"hello",[1,2,3])
tuple1[-1][-1] = "good"
print(tuple1)
#(1, 2, 3, 4, 5, True, 'hello', [1, 2, 'good'])
3. 删除元组
元组是不可变的,但是我们可以使用del语句删除整个元组
tuple1 = ('hello', 'hi')
del tuple1
print(tuple1)
#此时会报错
元组操作
1. 元组的连接/组合
tuple3 = tuple1 + tuple2
使用“+”连接,将tuple1与tuple2中的元素取出重新组合成一个新的元组并返回
tuple1 = (1,2,3,"hello","good",True,12.34)
tuple2 = (4,5,6)
print(tuple1+tuple2)
#(1, 2, 3, 'hello', 'good', True, 12.34, 4, 5, 6)
2. 元组的重复
tuple2 = tuple1 * n
功能:将tuple1中的元素重复n次输出到新的元组中
tuple1 = (1,"good",True,12.34)
print(tuple1*3)
#(1, 'good', True, 12.34, 1, 'good', True, 12.34, 1, 'good', True, 12.34)
3. 判断元素是否在元组中
元素 in 元组
判断元素是否在元组中存在,若存在则返回True,否则返回False
tuple1 = (1,2,3,"hello","good",True,12.34)
tuple2 = (4,5,6)
print(2 in tuple2) #False
print(2 in tuple1) #True
4. 元组的截取
tuple1[start:end:step]
start:默认0
end:默认len(tuple1)
step:默认1,取值可以为负
如下:
tuple1 = (1,2,3,"hello","good",True,12.34)
print(tuple1[:-1])
print(tuple1[:-1][1::-1])
print(tuple1[:-1][1::-1][-1])
print(tuple1[3::-1])
print(tuple1[:3:-1])
运行如下:
(1, 2, 3, 'hello', 'good', True)
(2, 1)
1
('hello', 3, 2, 1)
(12.34, True, 'good')
常见函数
1. max(tuple1)
功能:返回tuple1中最大值
tuple2 = (4,5,6)
print(max(tuple2)) #6
2. min(tuple1)
功能:返回tuple1中最小值
tuple2 = (4,5,6)
print(min(tuple2)) #4
3. tuple(list1)
功能:将列表转为元组
print(tuple([1,2,3,4]))
#(1, 2, 3, 4)
4. tuple1.count(x)
功能:统计x在tuple1中出现的次数
tuple1 = (4,5,6)
print(tuple1.count(5)) #1
5. tuple1.index(obj,start,end)
功能:在tuple1中查找obj,若找到则返回第一匹配到的下标值,若找不到则报错。查询范围[start,end),若不指定则查询整个元组
tuple1 = (1,2,3,"hello","good",True,12.34)
print(tuple1.index(3,0,3)) #2
print(tuple1.index(4,0,3)) #ValueError: tuple.index(x): x not in tuple
二维元组
tuple1 = (t1,t2,t3,…,tn)
当元组中的元素刚好又是元组的时候,我们称这个元组为二维元组
tuple1 = (1,2,3,"hello","good",True,12.34)
tuple2 = (4,5,6)
tuple3 = (tuple1,tuple2)
print(tuple3)
#((1, 2, 3, 'hello', 'good', True, 12.34), (4, 5, 6))
如tuple3我们就可以将其称为二维元组
二维元组的访问
tuple1[index1][index2]
index1:代表第index1个元组
index2:代表第index1个元组中第index2个元素
如下:
tuple1 = (1,2,3,"hello","good",True,12.34)
tuple2 = (4,5,6)
tuple3 = (tuple1,tuple2)
print(tuple3[0][-1]) #12.34