为了方便大家拷贝笔记,本文采用md源码格式
[toc]
# set 集合
- 作用:关系运算,去重
- 定义集合:{}内用逗号分隔每个元素都必须为**不可变类型**,元素不能重复,无序,一定是不能使用list,dict
## add
>add(self, *args, **kwargs) 添加,如果元素已经存在,这不起作用
```
E = {'a','b'}
E.add('c')
print(E)
结果:{'a', 'b', 'c'}
```
## clear
>clear(self, *args, **kwargs)
清空
```
E = {'a','b'}
E.clear()
print(E)
结果:set()
```
## copy
>copy(self, *args, **kwargs)
拷贝
```
E = {'a','b'}
v = E.copy()
print(v)
结果:{'b', 'a'}
```
## pop
>pop(self, *args, **kwargs)
随机拿走一个元素,并取值,如果该集合为空,则引发KeyError
```
E = {'a','b','v'}
v = E.pop()
print(v)
结果:v
print(E)
结果:{'a','b'}
```
## remove
>remove(self, *args, **kwargs)
移除,如果元素不是成员,则引发KeyError。
```
E = {'a','b','v'}
E.remove('a')
print(E)
结果:{'b','v'}
```
## discard (移除)
>discard(self, *args, **kwargs) 移除,如果元素不是成员,则什么都不做。
```
E = {"a",'b','v'}
E.discard('a')
print(E)
结果:{'b','v'}
```
## update
>update(self, *args, **kwargs)
批量添加,有相同的部分忽略
```
s1 = {'a','b','v'}
s2 = {'a','b','1'}
s1.update(s2)
print(s1)
结果:{'a','b','1','v'}
```
## difference 差集(-)
>difference(self, *args, **kwargs)
s1中存在,s2中不存在
```
s1 = {"a",'b','v','1','2'}
s2 = {"a",'b','v','3'}
v = s1.difference(s2)
print(s1 - s2) #可以使用 -
print(v)
```
## difference_update
>difference_update(self, *args, **kwargs)
s1中存在,s2中不存在,然后对s1清空,再重新复制
```
s1 = {"a",'b','v','1','2'}
s2 = {"a",'b','v','3'}
s1.difference_update(s2)
print(s1)
结果:{'1', '2'}
```
## intersection 交集(&)
>intersection(self, *args, **kwargs)
交集
```
s1 = {"a",'b','v'}
s2 = {"1",'b','v'}
v = s1.intersection(s2)
print(v)
print( s1 & s2)
{'v', 'b'}
{'v', 'b'}
```
## intersection_update
>intersection_update(self, *args, **kwargs)
取交集,然后对s1清空,然后在重新复制
```
s1 = {"a",'b','v'}
s2 = {"1",'b','v'}
s1.intersection_update(s2)
print(s1)
结果:{'b','v'}
```
## symmetric_difference 对称差集(^)
>symmetric_difference(self, *args, **kwargs)
两集合不同的元素
```
s1 = {'a','b','v'}
s2 = {'a','b','1'}
v = s1.symmetric_difference(s2)
print(v)
print(s1 ^ s2)
{'v', '1'}
{'v', '1'}
```
## symmetric_difference_update
>symmetric_difference_update(self, *args, **kwargs)
两集合不同的元素,然后对s1清空,然后在重新复制
```
s1 = {'a','b','v'}
s2 = {'a','b','1'}
s1.symmetric_difference_update(s2)
print(s1)
结果:{'1','v'}
```
## union 并集(|)
>union(self, *args, **kwargs)
并集
```
s1 = {'a','b','v'}
s2 = {'a','b','1'}
v = s1.union(s2)
print(v)
print(s1 | s2)
{'a', 'b', 'v', '1'}
{'a', 'b', 'v', '1'}
```
## isdisjoint 没有交集
>isdisjoint(self, *args, **kwargs)
是否没有交集
```
s1 = {"a",'b','v'}
s2 = {"1",'b','v'}
v = s1.isdisjoint(s2)
print(v)
结果:False
```
## issubset 子集(<=)
>issubset(self, *args, **kwargs)
s1 是否是 s2的子集
```
s1 = {'b','v'}
s2 = {"1",'b','v'}
v = s1.issubset(s2)
print(v)
print(s1 <= s2)
结果:True
结果:True
```
## issuperset 父集(> >=)
>issuperset(self, *args, **kwargs)
s1 是否是 s2的父集
```
s1 = {'b','v'}
s2 = {"1",'b','v'}
v = s1.issuperset(s2)
print(v)
print(s1 > s2)
结果:False
结果:False
```