集合定义
集合里面的元素是不可重复的;
s={1,1,2,3,4,2,2}print(s){1, 2, 3, 4}
如何定义一个空集合?
s1 = {} # 默认情况是dict, 称为字典print(s1,type(s1)){}
定义一个空集合
s2 = set([])print(s2,type(s2))set()
集合应用
列表去重
lee =[1,1,23,45,565,4,32,12,23,1]print(list(set(lee)))[32, 1, 4, 12, 45, 565, 23]
集合特性
集合支持的特性只有成员操作符。索引,切片,重复,连接均不支持
s={1,1,2,3,4,2,2}#print(s[0])报错,不支持索引,'set' object does not support indexing#print(s[:])报错,不支持切片,'set' object is not subscriptable#print(s*2)报错,不支持重复,unsupported operand type(s) for *: 'set' and 'int'#print(s+{12,3}),报错,不支持连接,unsupported operand type(s) for +: 'set' and 'set'for item in s: print(item,end=';') 1;2;3;4;Process finished with exit code 0
集合常用方法
增加元素
- add()
单个元素
s={1,2,3,4}s.add(5)print(s){1, 2, 3, 4, 5}
- update()
多个元素,只能以集合形式添加
s={1,2,3,4}s.update({5,8,0})print(s){0, 1, 2, 3, 4, 5, 8}
删除
- pop()
随机删除一个元素
s={1,2,3,4}s.pop()print(s){2, 3, 4}
- remove()
删除指定元素
s={1,2,3,4}s.remove(3)print(s){1, 2, 4}
交集,并集,差集
- 交集
s1 = {1, 3, 5, 7, 9, 11}s3 = {1, 3, 5, 7, 8, 10, 12}print(s1.intersection(s3))print(s1&s3){1, 3, 5, 7}{1, 3, 5, 7}
- 并集
s1 = {1, 3, 5, 7, 9, 11}s2 = {2, 4, 6, 8, 10, 12}print(s1.union(s2))print(s1 | s2){1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
- 差集
s1 = {1, 3, 5, 7, 9, 11}s3 = {1, 3, 5, 7, 8, 10, 12}print(s1.difference(s3)) #元素在s1中不在s3中print(s1-s3){9, 11}{9, 11}
对等差分
s1 = {1, 3, 5, 7, 9, 11}s3 = {1, 3, 5, 7, 8, 10, 12}print(s1.symmetric_difference(s3)) #找出两者不一样的元素,两者的并集-交集print(s1^s3){8, 9, 10, 11, 12}{8, 9, 10, 11, 12}