set 集合操作
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:woshinidaye ''' 集合两个功能: 1、去重。把一个列表变成一个集合,就自动去重了; 2、关系测试。测试两个列表的交集、并集、补集等关系; ''' a = [1,2,2,3,4,5] b = '1234567890' e = 'hello' print(a,'\n',set(a),'\n',b,'\n',set(b),'\n',e,'\n',set(e)) #自动吧重复了2去掉了 #集合业务无序的,因此也没有index print('parting_1'.rjust(30,'>').ljust(60,'<')) list_1 = [1,2,34,56,7,7,8,89] list_1 = set(list_1) list_2 = [4,4,5,6,7,1,2] list_2 = set(list_2) list_3 = set([1,2,7]) print(list_1,list_2) #求交集,同时存在list_1 和 list_2 print(list_1.intersection(list_2)) #Return the intersection of two sets as a new set print('>>>>>',list_1 & list_2) #并集,list_1 list_2的并集, print(list_1.union(list_2)) #Return the union of sets as a new set print('>>>>>',list_1 | list_2) #差集,只存在于list_1,不存在与list_2 print(list_1.difference(list_2)) #Return the difference of two or more sets as a new set. print('>>>>>',list_1 - list_3) #要么存在于list_1,要么存在于list_2,反正不能同时存在于两个list print(list_1.symmetric_difference(list_2)) #Return the symmetric difference of two sets as a new set print('>>>>>',list_1 ^ list_2) #判断是不是子集,是不是父级 print(list_1.issubset(list_2),list_3.issubset(list_1),list_1.issuperset(list_3)) #判断有没有交集,如果没得交集,就返回True,否则为False print(list_1.isdisjoint(list_2)) #Return True if two sets have a null intersection #集合的用法还有,add、clear、copy、discard、pop、remove ''' pop:Remove and return an arbitrary set element.Raises KeyError if the set is empty. remove:Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. discard:Remove an element from a set if it is a member.If the element is not a member, do nothing. ''' print('ending'.rjust(30,'>').ljust(60,'<'))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言