元组类型内置方法
一、元组(tuple)
元组是不可变的列表,即元组的值不可更改,因此元组一般只用于只存不取的需求。也因此元组可以被列表取代掉,所以元组相比较列表使用的很少。元组相比较列表的优点为:列表的值修改后,列表的结构将会发生改变,而元组只需要存储,因此列表在某种程度上而言需要占用更多的内存。
1.1 作用
描述多个爱好,多门课程
1.2 定义方式
在()内可以有多个任意类型的值,逗号分隔元素
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple:{hobby_tuple}")
--------------------------------------------------------
hobby_tuple:['run', 'read', 'trip', 'music']
name_str = ('jiayi') # ()只是普通包含的意思
name_tuple = ('jiayi',)
print(f"type(name_str): {type(name_str)}")
print(f"type(name_tuple): {type(name_tuple)}")
--------------------------------------------------------
type(name_str): <class 'str'>
type(name_tuple): <class 'tuple'>
1.3 内置方法
1.3.1优先掌握
1.按索引取值
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple:{hobby_tuple[0]}")
---------------------------------------------------------
hobby_tuple:run
2.切片
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple:{hobby_tuple[0:3:2]}")
----------------------------------------------------------
hobby_tuple:('run', 'trip')
3.长度
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple:{len(hobby_tuple)}")
-----------------------------------------------------
hobby_tuple:4
4.成员运算
hobby_tuple = ('run','read','trip','music')
print(f"run in hobby_tuple:{'run'in hobby_tuple}")
print(f"run not in hobby_tuple:{'run' not in hobby_tuple}")
---------------------------------------------------------
run in hobby_tuple:True
run not in hobby_tuple:False
5.for循环
hobby_tuple = ('run','read','trip','music')
for i in hobby_tuple:
print(i)
------------------------------------------------------
run
read
trip
music
6.count()
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple.count('run):{hobby_tuple.count('run')}") #查找run在元组中出现的次数
---------------------------------------------------------
hobby_tuple.count('run):1
7.index()
hobby_tuple = ('run','read','trip','music')
print(f"hobby_tuple.index('run'):{hobby_tuple.index('run')}") #查找run在元组中第一次出现的位置
---------------------------------------------------------
hobby_tuple.index('run'):0
1.4 有一个值还是多个值
多个值
1.5 有序(索引)or无序(索引)
有序
1.6 可变or不可变
不可变
二、元组和列表的区别
l = ['a','b','c','d']
print(f"l_id:{id(l[0])}")
l[0] = 'A'
print(f"l_id:{id(l[0])}")
-------------------------------------------------------
l_id:2426468149880
l_id:2426469793840
列表可变的原因:索引所对应的值的内存地址是可以变得
元组不可变的原因:索引所对应的值的内存地址是不可变的,也就是说只要索引对应值的内存地址没有改变,那么元组是始终没有改变的。