元组内置方法
元组:
什么是元组tuple:只可取不可更改的列表,元组一被创建就被写死了
1.作用
压缩数据,节省内存
2.定义方式
()内用逗号隔开多个元素(可以为任意数据类型)
i = (1,2,3)
j = tuple((1,2))
只有一个元素时,必须得加逗号并且逗号会打印出来
3.使用方法
1.索引取值
2.索引切片
3.for循环
4.成员运算
5.len长度
6.index获取元素所以
7.count计数
4.有序无序
有序
5.可变不可变
元组内元素值不可修改,不存在此概念
字典内置方法
字典
字符串/列表/字典
常用,他们三个就足够描述世间万物了
其他数据类型可以被替代-->
列表代替元组,redis数据库替代集合
1.作用
存储多个数据,对每个数据具有描述
2.定义方式
{}内用逗号隔开多个键key(具有描述意义,不能为可变数据类型):值value(任意数据类型)对
散列表(哈希表)
可变 == 不可哈希, 不可变 == 可哈希
i = {(1,2):'cql'}
print(i)
#key为元组是可打印,不会报错
# 0001
dic = {0: '功能1', 1: '功能2'}
print(dic)
#key为数字类型时类似于自定义字符编码
3.使用方法
优先掌握
1.按key取值
2.按key修改值/添加值,若key不存在则添加
3.for循环,循环的是key值
4.成员运算,判断的是key值
5.len长度
6.keys/values/items
print(dic.keys())
#获取所有key,看成列表
print(dic.values())
# 获取所有value,看成列表
print(dic.items())
# 获取所有键值对,以元组形式存 放在列表中
for i,j in dic.items():
print(i,j)
#类似于循环解压缩,i拿到key,j拿到value
需要掌握
1.get()获取
dic = {'a': 1, 'b': 2, 'c': 3}
print(dic.get('c','q'))
print(dic.get('b',100))
print(dic.get('e'))
print(dic)
# 字典中没有返回None,可以给定一个默认值
2.update:更新,类似于list的extend
3.setdefault 设置默认值
dic = {'a': 1, 'b': 2, 'c': 3}
dic.setdefault('a',10)
print(dic)
dic.setdefault('q','r')
print(dic)
#字典中有则不修改,没有则增加
4.有序无序
无序
5.可变不可变
可变
集合内置方法
集合
1.作用
1.进行交/并/差/补(对称差运算)
2.去重
3.乱序-->基于散列表实现-->因此对于数字而言不会乱序,但是对于其他会乱序
2.定义方式
{}内衣逗号隔开多个元素(不能为可变数据类型)
定义空集合
i = set()
j = {}
#只有大括号为字典类型
3.使用方法
1.交/并/差/补运算
i = {1,9,6,7,10}
j = {3,5,1,7}
print(i&j)
print(i|j)
print(i-j)
print(i^j)
2.add #添加集合元素
i.add('cql')
print(i)
3.remove/discard/pop
remove
有则删除返回值None没有则报错
discard
有没有都返回None,有还会删除
pop
随机删除一个,不能有参数
4.有序无序
无序
5.可变不可变
可变
深浅拷贝
拷贝
如果l2是l1的拷贝对象,则l1内部的任何数据类型的元素变化,则l2内部的元素也会跟着改变,因为可变类型值变id不点
浅拷贝
如果l2是l1的浅拷贝对象,则l1内的不可变数据类型的元素发生改变时l2不变,如果l1内的可变数据类型元素发生改变时l2会跟着改变
深拷贝
如果l2是l1的深拷贝对象,则l1内任何数据类型的元素改变,l2都不会改变
说明
1.拷贝/浅拷贝/深拷贝只针对可变数据类型
2.内置方法中的copy都是浅拷贝,比如列表中如果有可变数据类型,就不要使用copy方法,因为并不希望原数据与拷贝对象的变化会互相影响
数据类型总结
存值个数
存一个值: 整型/浮点型/字符串
存多个值:列表/元组/字典/集合
有序无序
有序: 字符串/列表/元组(序列类型)
无序:字典/集合
可变不可变
可变: 列表/字典/集合
不可变:整型/浮点型/字符串/元组
深浅拷贝
只针对可变数据类型,面试很大概率会问,周氏python独有的,而是一种语言独有的