空集合
>>> _set = set()
>>> _set
set()
添加:add、update
add:在原集合上直接添加存在或不存在元素。
update:在原集合上直接添加存在或不存在元素或序列
>>> _set = {'a','c'}
>>> _set.add('c') #可以添加已有元素,但原集合无改变
>>> _set
{'c', 'a'}
>>> _set.add('d')
>>> _set
{'c', 'd', 'a'}
>>> _set1={'a','c','b'}
>>> _set1.update('e')
>>> _set1
{'c', 'e', 'a', 'b'}
>>> _set1.update(['a','d'])
>>> _set1
{'d', 'a', 'c', 'e', 'b'}
删除:remove、discard、pop
remove:在原集合上删除;删除不存在元素报错。
discard:在原集合上删除;删除不存在元素不报错。
pop:在原集合上随机删除一个元素,并返回该元素。
>>> _set={'a','c','b'}
>>> _set.remove('d')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
_set.remove('d')
KeyError: 'd'
>>> _set.remove('c')
>>> _set
{'a', 'b'}
>>> _set={'a','c','b'}
>>> _set.discard('d')
>>> _set.discard('c')
>>> _set
{'a', 'b'}
>>> _set={'a','c','b'}
>>> _set.pop()
'c'
>>> _set.pop()
'a'
>>> _set
{'b'}
集合运算
>>> _set1 = {'a','c','d'}
>>> _set2 = {'a','b','e','c'}
>>> _set1|_set2 #|, 并集
{'d', 'e', 'a', 'b', 'c'}
>>> _set1&_set2 #&, 交集
{'a', 'c'}
>>> _set1-_set2 #补集1:-, 在第一个不在第二个的所有元素
{'d'}
>>> _set1^_set2 #补集2: ^, 只在一个集合里的所有元素
{'d', 'e', 'b'}