[7天速成Python——第四天]
字典为一个无序,键不重复且元素只能是键值对的可变容器
info = {"k1":123,"k2":999 }
键不能重复,重复数据会被覆盖
info = {"k1":123,"k1":999 }
print(k1)//999
键必须要可哈希类型
//可哈希:int,bool,str,tuple
//不可哈希:列表,字典
v1 = 数据类型
a = hash(v1)
print(a)//可哈希就不会报错
默认无序(python3.6之后就有序了)
info = {"k1":123,"k2":999 }
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
a = info.get("k1")
print(a)//123
若键不存在,则返回一个空(None)
a = info.get("k1","xxx")//当键"k1"不存在时,a为xxx,键存在则a为值
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
user = input("请输入用户名")
pwd = input("请输入密码:")
a = info.get(user)
if a == None:
print("用户不存在")
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
a = info.keys()//高仿列表
res = list(a)//高仿列表转化成python列表
print(a)//dict_keys(['k1','k2','a1','a2'])
for i in info.keys():
print(i)//循环输出
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
a = info.values()//高仿列表获取其值
print(a)//dict_values([123,999,True,["1","2" ]])
for i in info.valuess():
print(i)//循环输出
items获取所有的键值
info.items()
for i in info.items():
print(i)//循环输出("k1":123)
for i,j in info.items()://元素自动解包传给i和j
print(i,j)//循环输出("k1":123)
a,b = [11,22]//自动解包,a11,b22
a,b = (11,22)//自动解包,a11,b22
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
data = len(info)
索引为键,通过键取值
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
//读取值
data = info["name"]
写一个不存在的键索引是会报错的
info.get(键)//键不存在则不报错,返回None
//新增和修改值
info["k1"] = 100//键不存在则新增
//删除(删除不存在则会报错)
del info[键]
//判断键是否存在再删除
if 键 in info:
pass
键//获取所有键
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
a = info.keys()//高仿列表
res = list(a)//高仿列表转化成python列表
print(a)//dict_keys(['k1','k2','a1','a2'])
for i in info.keys():
print(i)//循环输出
值
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
a = info.values()//高仿列表获取其值
print(a)//dict_values([123,999,True,["1","2" ]])
for i in info.valuess():
print(i)//循环输出
键值
items获取所有的键值
info.items()
for i in info.items():
print(i)//循环输出("k1":123)
for i,j in info.items()://元素自动解包传给i和j
print(i,j)//循环输出("k1":123)
a,b = [11,22]//自动解包,a11,b22
a,b = (11,22)//自动解包,a11,b22
练习题
while True:
text = input("请输入:")
if text.upper() == Q:
break
text_list = text.split(",")
info(text_list[0]) = text_list[1]
for a,b in info.items():
print(a,b)
goods = [
{"1":111,"a":aaa},
{"2':222,"a":bbb},
{"3":333,"a":ccc},
{"4':444,"a":ddd}
]
for m in len(goods):
msg = "{}{}{}".format(m+1,goods[m]['1'],goods[m]['a'])
嵌套
info = {
"k1":123,
"k2":999,
"a1":True,
"a2":["1","2"]
}
info["k1"]//123
info["a2"][-1]//"2"
info["a2"].append(999)//"a2":["1","2",999],
if "k1" in info:
pass
if "k3" in info:
pass
else:
info["k3"] = 123//设置一个键值为"k3"的值为123
字典是可变类型
1.4补充
内部嵌套,字典可以套列表,可以互相嵌套,因为他们是容器:元组,列表,字典(键是可哈希)
1.5可哈希(查询索引速度快)不可哈希:字典和列表
小结
1.字符串str
独有功能:大写/小写/去除空白/分割/替换/join/是否数字/左右填充
公共功能:长度/索引/切片/for循环/in是否包含
2.列表list
独有功能:追加/插入/删除(值)/删除(索引)/清空/排序
公共功能:长度/索引(读,删,改)/切片(读,删,改)/for/in是否包含
3.元组
独有功能:无
公共功能:长度/索引/切片/for循环/in是否包含
4.字典dict
独有功能:get/keys/values/items
公共功能:len/索引(自己定义键)(读,删,改,添加)/for循环/in是否包含(键)
2,集合(set)
集合是一个无序,可变,元素必须是可哈希且不重复的容器。
2.1定义
v1 = {11,22,33,44}
无序—无索引切片操作
可变:v1.add(11)
不重复:添加相同元素其值不变
元素必须可哈希:不可哈希有列表,字典,集合
不希望重复的数据的集合可以用集合
定义空值:
空列表
v1 = []
v2 = list()
空元组
v1 = ()
v2 = tuple()
空字典
v1 = {}
v2 = dict{}
空集合
v1 = set()
独有功能
1.添加元素
v1 = {11,22}
v1.add{33}
v1.add{"xqs"}
print(v1)
2.删除元素
v1.discard(11)
删除元素不存在则无操作
3.交集
v1 = {11,111,23,44}
v2 = {11,09,878,55,44}
res = v1.intersection(v2)//会生成一个新集合//或者 res = v1 & v2
res//{11,44}
4.并集
res = v1.union(v2)// v1 | v2
5.差集
res = v1.difference(v2)//v1有v2没有//res = v1 - v2
公共
1.长度
v1 = {11,22,33}
data = len(v1)//3
2.for
v1 = {11,22,33}
for i in v1:
print(i)//顺序不固定
3.in (效率高)
v1 = {11,22,33}
if 11 in v1:
print("在")
容器之间的转换:
list tuple set#转换原则为用英文名字包裹一下
list = []
a = tuple(list)//列表变元组
元组或列表转换成集合时会自动去重
None类型表示空值
v1 = None//节省内存
布尔类型
True/False
以下为False的是0,“”,[],(),{},set(),None —>False,其他均为True
浮点型(float)
小数,有时会不太精确
v1 = 2.9
精确时要用decimal模块
import decimal
v1 = decimal.Decimal("0.1")
v2 = decimal.Decimal("0.1")
v3 = v1 + v2
字节类型(bytes)
name = "xqs"//str为字符串,底层是unicode编码
data = name.encode("utf-8")//字符串转换成字节
print(data)//b'\xxx\xxx\xxx \xxx\xxx\xxx \xxx\xxx\xxx'//三个字节一个汉字
data = name.encode("gbk")b'\xxx\xxx\xxx\xxx\xxx\xxx'两个字节
//字节转换成字符串
name = “str” #PEP8标准
只能普通的文本文件
三个基本步骤!
1.打开
2.操作
3.关闭
1.快速读写
1.打开文件
open("文件路径",模式)
a = open("1.txt",mode = "wb")//写文件的模式,变量代指打开的文件
2.写内容
name = "str\n"//unicode,加\n则自动换行
a.write(name.enicode("utf-8"))//以utf-8的形式写
3.关闭文件
a.close()
wb模式:文件不存在则创建文件,文件存在则清空文件
循环输入
a = open("1.txt",mode = "wb")
while True:
if a:
break
name = "str\n"//unicode,加\n则自动换行
a.write(name.enicode("utf-8"))//以utf-8的形式写
a.close()
2.追加文件
mode = ‘ab’//写在文件尾部
3.读取内容
mode = ‘rb’
#读取文件内容
data = a.read()//字节形式
data.decode('utf-8')
b = data_string.split("\n")通过\n来切割字符串
b = data_string.strip().split("\n")通过\n来切割字符串
读取大文件逐行读
a.readline()
for line in a:
line_string = line.decode('utf-8')
line_string = line_string.strip()
with上下文//忘记关闭文件
//打开文件并让这个文件等于变量file_object
with open("xxx.txt",mode = 'rb') as file_object :
//在缩进里写代码,离开缩进时自动关闭文件
打开文件模式
w b,写
a = open("xxx.txt",mode = "wb")
a.write("xqs".enicode("utf-8"))
a.close()
w,写
```
a = open(“1.txt”,mode = “w”,encoding = “utf-8”)
a.write(“xqs”)
a.close()
```
ab,追加
```
a = open(“xxx.txt”,mode = “ab”)
a.write(“xqs”.enicode(“utf-8”))
a.close()
```
a,追
```
a = open(“xxx.txt”,mode = “a”,encoding = “utf-8”)
a.write(“xqs”)
a.close()
```
r b,读
a = open(“xxx.txt”,mode = “rb”)
//读到压缩后的utf-8编码
b.read()//读所有
for line in a://读行
pass
data = b.decode(‘utf-8’)//解压,utf-8–>unicode
a.close()
r,读
a = open(“xxx.txt”,mode = “r”,encodind = “utf-8”)
b.read()//读所有,直接读取到字符串
a.close()