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}