元组
使用()将多个元素括起来,多个元素之间用逗号隔开
1.定义:元组是容器,可以同时存储多个数据,不可变的,有序的
不可变----不能增删改
有序---- 可以通过下标获取元素
2.元素可以是任何类型的数据
注意:如果元组的元素只有一个的时候,必须在元素后面加逗号

元组元素的增删改查
元组的元素不支持增删改
列表获取元素的方式元素都支持:tuple[下标],tuple[:]

3.可以通过在变量前加* 来获取部分元素

4.元组的运算
+,*,==,is,not in,in ---- 和列表一样

5.max() 获取元组中元素最大值,
min() 获取元组中元素最大值,
len() 获取元组长度
6.sorted()
可以通过sorted() 对元组进行排序,产生一个列表

字典
1.字典(dict)
字典是一个容器类的数据类型,可以用来存储多个数据(以键值对的形式存储)。可变的,无序
可变---是指可以增删改
无序---是指不能通过下标来获取值
{key1:value1, key2:value...}
2.字典的增删改
1.查---获取键值对应的value
获取字典的值,必须通过key来获取,获取的时候也只能获取单个
a. 字典[key] --- 通过key获取其对应的value
注意:key值必须是存在的,否则会报key erro

b.字典.get(key)--- 通过key获取字典对应的value
key不存在的时候,不会报错,会输出None

注意:确定key存在的时候使用[]语法,key可能不存在的时候使用get语法
c. 遍历字典
在for-in中拿到的是key的值

d.其他的遍历方式
for key in 字典.keys:
print(key) ----- 直接拿到key的值
for value in 字典.values:
print(value)-----直接拿到value的值

3.增(添加键值对)
a.字典[key] = value (key在字典中不存在)

4.修改(修改字典中的value)
字典[key]= value(key在字典中存在)

5.删(删除键值对)
del 字典[key] --- 通过key值删除对应的键值对

字典.pop(key) ----取出key对应的value

3.字典的相关操作
a.字典的相关运算
== : 判断两个字典的值是否相等
is: 判断两个字典的地址是否相等
in 和 not in: key in dict/ key not in dict

b.字典的相关函数
len(dict) 获取字典中键值对的个数

dict.clear() ---- 清空字典

dict.copy() ---- 将字典中的键值对复制产生一个新的字典

dict.fromkeys(序列,值) ---- 创建一个字典,序列中每个元素作为key,值作为value,

dict.get(key) ----key不存在时取None
dict.get(key,默认值 ) --- key不存在时取默认值

dict.values() --> 返回所有值对应的序列
dict.keys() --> 返回所有键对应的序列
dict.items() --> 将键值对转换成元祖,作为一个序列的元素
注意:返回的都不是列表,是其他类型的序列

字典.setdefault(key) --> 添加键值对,键是key,值是None
字典.setdefault(key,value) --> 添加键值对,键是key,值是value
注意:key存在的时候,对字典不会有任何操作(不会修改key对应的值)

字典1.update(字典2) --> 使用字典2中键值对去更新字典1。(已经存在的key就更新,不存在就添加)

集合(set)
1.什么是集合
集合是容器,可以同时存储多个数据,可变的,无序的,元素是唯一的
可变--- 可以增删改
无序---- 不能通过下标获取元素
元素的唯一 ---- 自带去重的功能
{元素1,元素2....}
元素:只能是不可变得数据

2.集合的增删改
a.集合因为是无序的,不能查找,只能通过for-in遍历

b.集合的增
set.add(元素)--- 在set中增加一个元素

集合1.update(序列)----> 将序列中的元素添加到集合1中

c.删除集合的元素
集合.remove(元素)---- 删除指定元素
3.集合的相关运算
集合的相关运算:是否包含,交集,并集,差集,补集
a.是否包含
集合1 >= 集合2 ----判断集合1中是否包含集合2
集合1 <= 集合2 ---- 判断集合2中是否包含集合1

b.交集,运算符---&

c.并集 ,运算符 |
set1 = {1,2,3,4}
set2 = {8,9,3,4}
print(set1 | set2)
#{1,2,8,9}
d.求差集
集合1 - 集合2 ---求集合1中除了集合2以外的部分
set1 = {1,2,3,4}
set2 = {8,9,3,4}
print(set1 - set2)
#{1,2}
e.求补集 运算符 ^
set1 = {1,2,3,4}
set2 = {8,9,3,4}
print(set1 ^ set2)
#{1,2,8,9}
数据类型的转换
整型: int
转换为整型 int()
浮点型:float
转换为浮点型 float()
布尔:bool
转换为布尔: bool()
注意:所有的数据都可以转换为bool,为0为空时值为False,其余为True

字符串str
转换为字符串 str()
列表 list
转换为列表 list()
字典转换为列表将字典中的key转换为列表中元素
元组 tuple
转换为元组 tuple()
字典 dict
转换为字典 dict()
序列的每个元素有两个值的数据才能转换成字典
集合set
转换为集合 set()
网友评论