- 特性
- 无序,不重复的数据组合,用{}表示,eg:{1,2,3,4,5,6}
- 用途
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之间的交集,差集,并集,对称差集,包含(子集和超集,相交和不相交)关系
- 基本语法
- set():创建一个空集合,用set()创建,不能直接用s = {},这是创建一个空字典
-
s = set() print(type(s)) # =><class 'set'>
- add:往集合中添加一个元素,如果添加的元素集合中已有,则集合没有任何变化,只能添加不可变数据
-
s = {1,2,3,4,5} s.add(1) print(s) # =>{1, 2, 3, 4, 5} s.add(6) print(s) # =>{1, 2, 3, 4, 5, 6}
- update:往集合中添加多个元素,自动去重
-
s = {1,2,3,4,5} s.update({1,2,6,7,8}) print(s) # =>{1, 2, 3, 4, 5, 6, 7, 8}
- discard:删除指定元素,如果要删除的元素集合中不存在,do nothing
-
s = {1,2,3,4,5} s.discard(1) print(s) # =>{2, 3, 4, 5}
- remove:删除指定元素,如果要删除的元素集合中不存在,报错
-
s = {1,2,3,4,5} s.remove(1) print(s) # =>{2, 3, 4, 5} s.remove(6) # =>报错
- pop:随机删除一个元素,无序的,当集合为空时,报错
-
s = {1,2} s.pop() print(s) # =>{2} s.pop() s.pop() # =>报错
- clear:清空
-
s = {1,2,3,4,5} s.clear() print(s) # =>set()
- copy:浅复制
-
s = {1,2,3,4,5} s1 = s.copy() print(s1) # =>{1,2, 3, 4, 5}
-
difference:差集,差集后的结果是一个新的集合
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = s1.difference(s2) print(s3) # =>{1, 2, 3} s3 = s1-s2 print(s3) # =>{1, 2, 3} s4 = s2.difference(s1) print(s4) # =>{8, 6, 7} s4 = s2-s1 print(s4) # =>{8, 6, 7}
-
difference_update:删除s1集合中含有s2集合中的元素,并返回给s1
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = s1.difference_update(s2) print(s1) # =>{1, 2, 3}
-
intersection:交集,交集后的结果是一个新的集合
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = s1.intersection(s2) print(s3) # =>{4, 5} s3 = s1 & s2 print(s3) # =>{4, 5} s3 = s2.intersection(s1) print(s3) # =>{4, 5} s3 = s2 & s1 print(s3) # =>{4, 5}
-
intersection_update:将s1和s2的交集更新给s1
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s1.intersection_update(s2) print(s1) # =>{4, 5}
-
union:并集
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = s1.union(s2) print(s3) # =>{1, 2, 3, 4, 5, 6, 7, 8} s3 = s1 | s2 print(s3) # =>{1, 2, 3, 4, 5, 6, 7, 8}
-
isdisjoint:判断两个集合是否有交集,如果没有,返回True,如果有,返回False
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = {8,9} print(s1.isdisjoint(s2)) # => False print(s1.isdisjoint(s3)) # =>True
-
issubset:判断s2是否是s1的子集,如果是,则True,or,False
s1 = {1,2,3,4,5} s2 = {4,5} print(s2.issubset(s1)) # =>True
- issupper:判断s1是否是s2的超集
-
s1 = {1,2,3,4,5} s2 = {4,5} print(s1.issuperset(s2)) # =>True
- symmetric_difference:对称差集
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s3 = s1.symmetric_difference(s2) print(s3) # =>{1, 2, 3, 6, 7, 8} s3 = s2.symmetric_difference(s1) print(s3) # =>{1, 2, 3, 6, 7, 8}
- symmetric_difference_updata:将对称差集更新给s1,或者s2
-
s1 = {1,2,3,4,5} s2 = {4,5,6,7,8} s1.symmetric_difference_update(s2) print(s1) # =>{1, 2, 3, 6, 7, 8} s2.symmetric_difference_update(s1) print(s2) # =>{1, 2, 3, 4, 5}
- 其他用法:
- in ,not in 判断某元素是否在集合内
- == ,!=判断两个集合是否相等