元组(tuple)
有序(有索引,定义和显示顺序是一致的)、不可变、可重复、可以存放任何类型的数据(不可变的)
1).tuple的格式
tp1 = ("name","age",23,"height","address","job") tp1 = (name,job) = ["chen","IT"] tp1 = () tp1 = ("python",) print(tp1,type(tp1))
2).tuple的相关操作和函数
由tuple不可变的特点可知,元组中的元素是无法进行单独更改,增加和删除的。
(1).查:
获取元组中的元素(切片)
tp2 = ("name","age",23,"height","address","job") print(tp2[0],tp2[3]) #根据索引位置获取元组中的元素print(tp2[1:5:1]) #切片得到索引内的元素
index和count函数
tp2 = ("name","age",23,"height","address","job") print(tp2.index("age")) #通过元素名找到该元素所在位置索引 print(tp2.count("age")) #查找该名称元素的在列表中个数(有多个相同元素的时候)
(2).对元组整体的操作
合并两个元组“+”,得到一个新的元组
tp3 = ("name","age",23,"height","address","job") tp4 = ("name",(23,"python")) tp5 = tp3 + tp4 print(tp5)
元组的删除,只能借助与del函数,
tp6 = ("name","age",23,"height","address","job") del tp6print(tp6) #tp6被回收,无地址,报错
原文地址:https://www.cnblogs.com/chen-sang-python/p/9677632.html
时间: 2024-10-11 21:25:31