Python学习笔记-元组(tuple)
作者:互联网
什么是tuple
tuple
元组,可以盛放多种数据,类似列表但是原生不支持删除,添加或修改,仅支持查找
创建
tuple0 = () # 空的元组
tuple1 = (0,) # 仅有1个元素的元组
tuple2 = (1,2,3,4,5,6)
访问
- 支持通过
索引
访问 - 支持
切片
访问
增删改查
-
查找
-
index()
索引方式查找元素tuple1 = (1,2,3,4,5,6,0,5) print(tuple1.index(5)) print(tuple1.index(5,5)) ============================== 4 7
-
-
曲线救国的增删改–利用强制类型转换
利用list与tuple之间的强制类型转换完成增删改操作
实际上相当于是对原tuple重新初始化
tuple1 = (0,1,2) list1 = list(tuple1) list1.append(3) list1.pop(1) tuple1 = tuple(list1) print(tuple1) ================================ (0, 2, 3)
其他方法
-
.count()
对指定元素计数tuple1 = (1,2,3,4,5,5) print(tuple1.count(5)) ============================== 2
-
sorted()
排序,排序之后返回一个list型结果默认升序排列,加参数
reverse = True
实现降序排列或者排序完成后添加
.reverse()
实现翻转tuple1 = (1,3,5,2,4,6,9,7) list1 = sorted(tuple1) # 返回一个list型,用list1接一下再转成tuple tuple2 = tuple(list1) # 强制类型转换,将list转为tuple print(list1) print(tuple2) ===================================== [1, 2, 3, 4, 5, 6, 7, 9] (1, 2, 3, 4, 5, 6, 7, 9)
-
max()
求最大值tuple1 = (1,5,3,7,6,8,4,0) print(max(tuple1)) ======================================= 8
-
min()
求最小值tuple1 = (1,5,3,7,6,8,4,0) print(min(tuple1)) ======================================= 0
-
sum()
求和tuple1 = (1,5,3,7,6,8,4,0) print(sum(tuple1)) ======================================= 34
支持的符号
+
连接两个元组,成为一个新元组*
将一个元组重复N次,成为一个新元组in
检查元素是否在元组中存在is
检查两个元组地址是否相同[ ]
元组支持索引操作[:]
元组支持切片操作
标签:tuple,Python,list,list1,元组,tuple1,print 来源: https://blog.csdn.net/Lance_Lewu/article/details/104207465