8、集合类型、文件处理
补充:setdefault与update的区别
例:d={‘’name'':''egon'',''age'':18,''gender'':''xxx''}
d.update({''gender'':''male''})
res = d.setdefault(''gender'',''male'')
print(d)输出结果为d={‘’name'':''egon'',''age'':18,''gender'':''male''}
print(res)输出结果为d={‘’name'':''egon'',''age'':18,''gender'':''xxx''}
一、集合
例:
pythons = ["tom","jack","alex","egon","lxx"] linuxs = ["lili","hanmeimei","张三","egon","lxx","jay"] #找出即学linux与pythopn的学生 l=[] for name in pythons: if name in linuxs: l.append(name) print(l)
通过上述的for循环可以达到目的,但是集合在比较方面有便利之处
1、用途:
去重:
(1)无法保证顺序
msg = "hello" res=set(msg) print(''.join(res)) names = ['egon','lxx','lili',"egon","egon"] print(list(set(names)))
(2)只能针对不可变的元素去重
students_info = [ {"name":"egon","age":18,"gender":"male"}, {"name":"tom","age":19,"gender":"male"}, {"name":"jack","age":38,"gender":"female"}, {"name":"egon","age":18,"gender":"male"}, {"name":"egon","age":18,"gender":"male"}, ] new_l = [] for info in students_info: if info not in new_l: new_l.append(info) print(new_l)
(3)集合内的元素无法重复,只能打印出一个
2、集合内的关系运算
定义:在{}内用逗号分隔开多个元素
数据类型转换:工厂函数为set
res = set("hello") print(res) s = set() print(s,type(s))
3、通常操作与内置方法
pythons = {"tom","jack","alex","egon","lxx"} linuxs = {"lili","hanmeimei","张三","egon","lxx","jay"}
(1)交集:取两个集合的共同部分
print(pythons & linuxs) print(pythons.intersection(linuxs)) pythons = pythons & linuxs pythons.intersection_update(linuxs)
(2)并集:两个集合合并到一起
print(pythons | linuxs) print(pythons.union(linuxs))
(3)差集:一个集合减掉另一个集合共同的部分
#只学了python的学生姓名 print(pythons - linuxs) print(pythons.difference(linuxs)) #只学了linux的学生姓名 print(linuxs - pythons)
(4)交叉补集/对称补集:两个集合相互减,然后再并到一起
res = (pythons - linuxs) | (linuxs - pythons) res = pythons ^ linuxs print(res) print(pythons.symmetric_difference(linuxs))
(5)父子集合:包含关系,当一个集合完全包含了另一个集合才能当爹QAQ
s1 = {1,2,3} s2 = {3,4,5} print(s1 >= s2) print(s2 <= s1) s1 = {1,2,3} s2 = {1,2} print(s1 >= s2) print(s1.issuperset(s2)) print(s2 <= s1) print(s2.issubset(s1))
**需要掌握的
1、update(增加)
s1.update({3,4,5})
print(s1)
2、s1.add(增加)
s1.add(4)
print(s1)
3、删除
s1 = {11,22,33,44,55,"xx","yy","zz","aa"} s1.remove(3) print(s1) s1.remove(333333333) s1.discard(333333333) print(s1) res=s1.pop() print(s1) print(res) s1.clear() print(s1)
4、拷贝
s1.copy
5、isdisjoint
用于判断这两个集合是否存在共同的元素,如果完全不同输出为True
s1 = {1,2,3} s2 = {4,5,6} print(s1.isdisjoint(s2)) #输出结果为True
总结:集合可以存多个值,是无序的,是可变的
二、文件处理
(1)什么是文件
文件是操作系统提供给用户或者应用程序操作硬盘的一种机制
(2)为何要用文件
读写文件------->存取硬盘
应用程序: open()
操作系统: 打开文件
计算机硬件: 硬盘空间
(3)如何使用文件
打开文件
读/写
关闭文件
f = open(r"a\a.txt",mode="rt",) #f的值-》文件句柄,文件对象 res = f.read() print(res,type(res)) f.close() # 回收操作系统的资源 print(f) f.read() with open(r"a\a.txt",mode="rt",) as f,\ open(r"a\b.txt",mode="rt",) as f1: res = f.read() with open(r"a\a.txt",mode="rt",) as f: for line in f: # print(line) res=line.strip('\n').split(':') print(res)