增:
add
a = {1,2,3} a.add(4) print(a) #{1, 2, 3, 4}
删:
discard、remove、pop
a = {1,2,3} a.remove(1) print(a) a.discard(1) print(a) a.discard(2) print(a) #{2, 3} #{2, 3} #{3}
改(不支持,也不支持切片,无索引):
a = {1,2,3} print(a[0]) # File "E:/pythondir/Day01/task02.py", line 2, in <module> print(a[0]) TypeError: 'set' object is not subscriptable
查:
in or not in
并集:
| 、union
a = {1,2,3,4,5} b = {2,3,5,6,7,8,9} print(a | b) print(a.union(b)) #{1, 2, 3, 4, 5, 6, 7, 8, 9} #{1, 2, 3, 4, 5, 6, 7, 8, 9}
差集:
-、difference
a = {1,2,3,4,5} b = {2,3,5,6,7,8,9} print(a - b) print(a.difference(b)) print(a.difference_update(b)) #去掉交集,并更新 print(a) #{1, 4} #{1, 4} #None #{1, 4}
交集:
&、intersection
a = {1,2,3,4,5} b = {2,3,5,6,7,8,9} print(a & b) print(a.intersection(b)) #{2, 3, 5} #{2, 3, 5}
对称差集(两者并集去掉交集):
^、symmetric_difference
a = {1,2,3,4,5} b = {2,3,5,6,7,8,9} print(a ^ b) print(a.symmetric_difference(b)) #{1, 4, 6, 7, 8, 9} #{1, 4, 6, 7, 8, 9}