Python基础(六)之数值类型元组
Python基础六之数值类型元组1、简介元组 在Python中是内置的数据结构之一是一个不可变的序列,切可以是任何类型数据。元组的元素放在小括号内。一般我们希望数据不改变的时候使用不可变与可变的区别不可变序列字符串、元组没有增删改操作可变序列 列表、字典可以对序列执行增删改操作对象的地址不发生变化2、 创建元组2.1、直接创建格式 元组名称 元素1, 元素2, 元素3 或者 元组名称 元素1, 元素2, 元素3空原则 元组名称 或者 元组名称 tuple()特殊的元组 元组名称 元素1, s_tuple(1,2,3,4,5)print(s_tuple数据类型,type(s_tuple))print(s_tuple数据,s_tuple)s_tuple21,2,3,4,5print(s_tuple2数据类型,type(s_tuple2))print(s_tuple2数据,s_tuple2)s_tuple数据类型 class tuple s_tuple数据 (1, 2, 3, 4, 5) s_tuple2数据类型 class tuple s_tuple2数据 (1, 2, 3, 4, 5) 2.2、使用内置函数tuple()s_tupletuple((P,y,t,h,o,n))print(s_tuple数据类型,type(s_tuple))print(s_tuple数据,s_tuple) s_tuple数据类型 class tuple s_tuple数据 (P, y, t, h, o, n) 2.3、 将迭代系列转化为元组sPythons_listlist(s)s_tupletuple(s)print(s_tuple)# (P, y, t, h, o, n)s_list_to_tupletuple(s_list)print(s_list_to_tuple)# (P, y, t, h, o, n)【注】只包含一个元素的元组需要使用逗号和小括号来表示若没有添加逗号Python会默认括号本身内数据本身的数据类型s_tuple(str)print(错误的元组创建方式,type(s_tuple))# 错误的元组创建方式 class strs_tuple(str,)print(正确的元组创建方式,type(s_tuple))# 正确的元组创建方式 class tuple3、遍历元组在Python 中使用for循环遍历元组的元素s_tuple(1,2,3,4,5)forelins_tuple:print(el) 1 2 3 4 5 s_tuple_empty()forelins_tuple_empty:print(el)4、 元组解包将元组tuple中的元素赋值给变量s_tuple(P,y,t,h,o,n)a,b,c,d,e,fs_tupleprint(a ,a)print(b ,b)print(c ,c)print(d ,d)print(e ,e)print(f ,f) a P b y c t d h e o f n s_tuple(P,y,t,h,o,n)a,b,c,d,e,f,*gs_tupleprint(a ,a)print(b ,b)print(c ,c)print(d ,d)print(e ,e)print(f ,f)print(g ,g) a P b y c t d h e o f n g [] s_tuple(P,y,t,h,o,n)*a,b,cs_tupleprint(a ,a)print(b ,b)print(c ,c) a P b [y, t, h, o] c n 【注】元组解包的时候前面的变量数量必须与元组的元素数量一致。若变量的数量与元组中元素的数量不一致时则在某个变量的前面加一个* 这样会将多余的变量以列表的格式转化到该变量中5、 检查元素是否在元组中使用in或者not ins_tuple(P,y,t,h,o,n)print(Helloins_tuple)# Falseprint(Hellonotins_tuple)# Trueprint(tins_tuple)# Trueprint(tnotins_tuple)# False6、 查询元组元组没有增删改操作但可以进行查询6.1 index() 从元组中找出某个值第一个匹配项的索引s_tuple(P,y,t,h,o,n)print(s_tuple.index(P))# 0print(s_tuple.index(hello))# 报出错误 ValueError: tuple.index(x): x not in tuple6.2、count() 统计元组中某个元素出现的次数s_tuple(H,e,l,l,o)print(s_tuple.count(l))# 2print(s_tuple.count(h))# 07、 删除元组元组虽然不能新增和修改、且删除单独的元素但可以将元组整体全部删除s_tuple(H,e,l,l,o)dels_tupleprint(s_tuple)# NameError: name s_tuple is not defined. Did you mean: tuple?8、 其他操作8.1、 获取元组的长度s_tuple(H,e,l,l,o)print(len(s_tuple))# 58.2、 获取元组的最大值或最小值s_tuple(H,e,l,l,o)print(max(s_tuple))# oprint(min(s_tuple))# H9、 元组与列表对比列表是可变的创建完成后可以对列表进行增删改查操作。元组是不可变的创建完成后其内容和大小均不可发生改变元组虽然不可变但可以可以将两个元组合并成一个新的元组切不需要为新原则分配额外的空间s_tuple1(P,y,t)s_tuple2(h,o,n)print(s_tuple1s_tuple2)# (P, y, t, h, o, n)