python--集合
set集合的去重机制 : 先调用hash,再调用eq,eq不是每次都触发,只有hash值相等的时候才会触发
dic1 = set() # 空集合 dic = {"葫芦娃", "变形金刚"} print(type(dic))
结果:
<class 'set'>
集合的常用操作
list1 = set([1, 4, 5, 7, 3, 6, 7, 9]) # 将列表转为集合 list2 = set([2, 6, 0, 66, 22, 8, 4]) list3 = set([1, 3, 7]) print(set(list1), set(list2)) # 转换成集合,去掉重复的值,保留唯一值 print(list1.intersection(list2)) # 取两个集合的交集 print(list1.union(list2)) # 并集,两个集合合并,去掉 重复的,保留唯一值 print(list1.difference(list2)) # 差集list1里有list2里没有的 print(list1.issubset(list2)) # 子集,输出True或False print(list1.issuperset(list3)) # 父集,list3里的都在list1里 print(list1.symmetric_difference(list2)) # 对称差集,去掉重复的,放到一个集合里 print(list1.isdisjoint(list2)) # 没交集返回为True,有交集返回False
结果:
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8} {4, 6} {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22} {1, 3, 5, 7, 9} False True {0, 1, 2, 66, 3, 5, 7, 8, 9, 22} False
list1 = set([1, 4, 5, 7, 3, 6, 7, 9]) list2 = set([2, 6, 0, 66, 22, 8, 4]) list3 = set([1, 3, 7]) print(set(list1), set(list2)) # 转换成集合,去掉重复的值,保留唯一值 print(list1 & list2) # 交集 print(list1 | list2) # 并集 unio print(list1 - list2) # 差集 differenc,跟位置有关系 print(list1 ^ list2) # 对称差集
结果:
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8} {4, 6} {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22} {1, 3, 5, 7, 9} {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
list1 = set([1, 4, 5, 7, 3, 6, 7, 9]) list2 = set([2, 6, 0, 66, 22, 8, 4]) list3 = set([1, 3, 7]) print(set(list1), set(list2)) # 转换成集合,去掉重复的值,保留唯一值 list1.add(777) # 添加一项 print(list1) list1.update([555, 666, 888]) # 添加多项 print(list1) list1.remove(555) # 删除555 print(list1)
结果:
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8} {1, 3, 4, 5, 6, 7, 9, 777} {1, 3, 4, 5, 6, 7, 9, 777, 555, 888, 666} {1, 3, 4, 5, 6, 7, 9, 777, 888, 666}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2019-07-12 django -- 模版语言之过滤器Filters和for循环