Python学习-0610
一、集合剩余内容
一、关系运算
firends1 = {"zero", "kevin", "jason", "egon"}firends2 = {"jy", "ricky", "jason", "egon"}1、取二者的共同好友:交集res = firends1 & firends2print(res)2、取二者所有的好有有哪些:并集res=firends1 | firends2print(res)3、取第一个人独有的好友:差集res=firends1 - firends2print(res)res=firends2 - firends1print(res)4、求两个用户独有的好友们(即去掉共有的好友):对称差集/交叉补集res1=firends1 - firends2res2=firends2 - firends1print(res1 | res2) p
rint(firends1 ^ firends2)5、父子集:一个集合包含另外一个集合,他们才有父子集的关系s1 = {1, 2, 3}s2 = {3, 4, 5}print(s1 > s2) # Falseprint(s1 < s2) # Falseprint(s1 == s2) # False集合1>集合2 结果True时,意味着集合1内的元素完全包含了集合2s1={1,2,3}s2={1,2}print(s1 > s2) # 结果True,代表s1是s2的父集print(s2 < s1) # 结果True,代表s2是s1的子集 二、常用操作与内置方法s1 = {3, 2, 1}for item in s1: print(item)s1 = {3333, "aaa", 222, "bbb", 111}1、s1.update()print(id(s1))s1.update({3,4,5})print(s1)print(id(s1))2、
s1.clear()3、s1.pop()res=s1.pop() print(s1)print(res)4、s1.remove() s1 = {3333, "aaa", 222, "bbb", 111}res = s1.remove(3333)print(s1)print(res)5、s1.discard() s1 = {3333, "aaa", 222, "bbb", 111}res=s1.discard(3333)print(s1)print(res)不同的地方:当删除的元素不存在时,s1.discard不会报错s1.discard(555555)s1.remove(555555) # 指定元素不存在则报错s1.add()s1 = {3333, "aaa", 222, "bbb", 111}s1.add(555555555)print(s1)s1.isdisjoint(s2) # 如果s1与s2没有共同的元素则返回Trues1={1,2,3} s2={4,5} print(s1.isdisjoint(s2))总结集合set:存多个值 无序 set集合是可变类型二、文件操作
1、什么是文件文件是操作系统提供给用户/应用程序操作硬盘的一个虚拟单位/功能应用程序/用户对文件的读写操作都是在向操作系统发起系统调用操作系统接收到调用请求后,会将该请求转换成具体的硬盘操作2、为何要用文件应用程序操作文件为了将内存中的数据永久保存到硬盘中去3、如何操作文件一:文件的基本操作文件的路径:找到文件的地址绝对路径:r'C:\a\b\c\new.txt'相对路径:相对于当前程序所在文件夹往后找,r"aaa/a.txt"f = open(r"aaa/a.txt", mode='rt', encoding='utf-8')二:文件的模式2.1 控制文件读写内容的模式(不能单独使用,必须与rwa结合使用)t:(默认的)1、读写内容都是以字符串为单位2、只适用于文本文件3、必须指定encoding参数b:1、读写内容都是以bytes为单位2、适用于所有文件3、一定不能指定encoding参数2.2 控制文件读写操作的模式r:(默认的)1、只读模式2、当文件不存在时则报错3、当文件存在时文件指针跳到文件开头f = open('b.txt', mode='rt', encoding='utf-8')data = f.read()print(data)f.close()w:1、只写模式2、当文件不存在会创建一个空文件,然后文件指针跳到文件开头3、当文件存在时文件内容会被清空,然后文件指针跳到文件开头f = open('c.txt', mode='wt', encoding='utf-8')name = input('>>: ')f.write(name)f.write("egon\n")f.write("张三\n")f.write("李四\n")f.close()a:1、只追加模式2、当文件不存在会创建一个空文件,然后文件指针跳到文件末尾3、当文件存在时文件内容不会被清空,文件指针跳到文件末尾f = open('d.txt',mode='at',encoding='utf-8')f.write('aaa\n')f.write('bbb\n')f.write('ccc\n')f.close()w与a模式的相同点在文件打开了没有被关闭的情况下,连续的写入,新写入的内容总是跟在老内容之后w与a模式的不同点在文件关闭了重新打开的情况下,a模式永远把文件指针放到文件末尾# 案例一:编写一个用户注册功能,注册的内容是账号名和密码名# name = input("请输入您的账号>>:").strip()# pwd = input("请输入您的密码>>:").strip()# # 账号密码合法性校验# f = open('db.txt',mode='at',encoding='utf8')# f.write("%s:%s\n" %(name,pwd))# f.close()# 案例二:编写一个用户验证功能,账号密码来自于文件inp_name = input("请输入您的账号>>:").strip()in_pwd = input("请输入您的密码>>:").strip()f = open('db.txt', mode='rt', encoding='utf-8')for line in f: name, pwd = line.strip("\n").split(':') if inp_name == name and in_pwd == pwd: print('登录成功') breakelse: print('账号密码输入错误')f.close()
浙公网安备 33010602011771号