元组概念和创建元组
概念:
1.本质:是一种有序集合
2.特点:与列表非常相似、一旦初始化就不能修改、使用小括号
创建:
1.创建空元组
tuple1 = ()
print(tuple1) #()
2.创建带有元素的元组
元组中的元素的类型可以不同
tuple2 = (1, 2, 3, "good", True)
print(tuple2) #(1, 2, 3, "good", True)
3.定义只有1个元素的元组
tuple3 = (1,) #就算只有一个元素,该元素后面也要有逗号,否则不为元组
print(tuple3) #(1,)
print(type(tuple3)) #<class 'tuple'>
元组访问
格式:元组名[下标],下标不能越界,否则会报错
tuple4 = (1, 2, 3, 4, 5)
print(tuple4[0]) #1
print(tuple4[5]) #下标不能越界
print(tuple4[-1]) #获取最后一个元素,5
print(tuple4[-2]) #获取倒数第二个元素,4
print(tuple4[-6]) #下标不能越界,倒数从-1开始,-5是最后一个元素,-6才越界
tuple5 = (1, 2, 3, 4, 5, [5, 6 ,7])
tuple5[0] = 100 #报错,报错内容:TypeError: 'tuple' object does not support item assignment
tuple5[-1] = [7, 8, 9] #报错,报错内容:TypeError: 'tuple' object does not support item assignment
tuple5[-1][0] = 500 #可以,元组元素里的内容可以被改变
print(tuple5) #(1, 2, 3, 4, 5, [500, 6, 7])
删除元组:
格式:del 元组名
tuple6 = (1, 2, 3, 4, 5)
del tuple6
print(tuple6) #报错,报错内容:NameError: name 'tuple6' is not defined
元组操作
1.元组相加 -- +
tuple7 = (1, 2, 3)
tuple8 = (4, 5, 6)
print(tuple7 + tuple8) #(1, 2, 3, 4, 5, 6)
2.元组重复 -- *
tuple9 = (1, 2, 3)
print(tuple9 * 3) #(1, 2, 3, 1, 2, 3, 1, 2, 3)
3.判断元素是否在元组中 -- in
tuple10 = (1, 2, 3)
print(4 in tuple10) #False
4.元组的截取
格式: 元组名[起始下标:结尾下标],会截取[起始下标,结尾下标)闭开区间内的数据
tuple11 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(tuple11[3:7])
print(tuple11[3:])
print(tuple11[:7])
元组函数
1.len(t),返回元组中元素的个数
tuple13 = (1, 2, 3, 4, 5)
print(len(tuple13)) #5
2.max(t),返回元组中元素的最大值
tuple14 = (1, 2, 3, 4, 5)
print(max(tuple14)) #5
3.min(t),返回元组中元素的最小值
tuple15 = (1, 2, 3, 4, 5)
print(min(tuple15)) #1
4.tuple(l),将列表转成元组
list1 = [1, 2, 3, 4, 5]
print(tuple(list1)) #( 1, 2, 3, 4, 5)
网友评论