去重
定义一个集合:
>>> a = {1,2,3,4,5,2,1}
>>> a
{1, 2, 3, 4, 5}
增加
>>> a.add(6)
>>> a
{1, 2, 3, 4, 5, 6}
删除
ch>>> a.discard(5)
>>> a
{1, 2, 3, 4, 6}
>>> a.discard(5) #没有不报错
>>> a
{1, 2, 3, 4, 6}
>>> a.pop() #随机删
1
>>> a.pop()
2
>>> a
{3, 4, 6}
>>> a.remove(3)
>>> a
{4, 6}
>>> a.remove(3) #没有报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 3
查
>>> 3 in a
False
>>> 4 in a
True
交集
>>> a
{'efe', 'aaa', 'ccc', 'sfs', 'bbb', 'aag'}
>>> b = {'sfg','gjk','aaa','ggg','ccc'}
>>> b
{'sfg', 'ggg', 'gjk', 'aaa', 'ccc'}
>>> print(a&b)
{'aaa', 'ccc'}
合集
>>> print(a|b)
{'sfg', 'ggg', 'gjk', 'efe', 'aaa', 'ccc', 'sfs', 'bbb', 'aag'}
差集
>>> print(a-b) #a有,b没有
{'sfs', 'efe', 'bbb', 'aag'}
>>> print(b-a) #b有,a没有
{'sfg', 'gjk', 'ggg'}
对称差集,共有的t出去
>>> print(b^a)
{'ggg', 'efe', 'sfs', 'sfg', 'gjk', 'bbb', 'aag'}
判断是不是不相交
>>> a.isdisjoint(b) #是不是不相交,no
False
>>> print(a.isdisjoint(b))
False
>>> a.isdisjoint({2,3}) #完全不相交,yes
True
是否子集
>>> {1,2}.issubset({1,2,4})
True
是否父集
>>> {1,2}.issuperset({1})
True
difference差集
>>> {1,2}.difference({1})
{2}
intersection交集
>>> {1,2}.intersection({1})
{1}
symmetric_difference对称差集
>>> a = {1,2,3}
>>> b = {2,4,5}
>>> a.symmetric_difference(b)
{1, 3, 4, 5}
union合集
>>> a.union(b)
{1, 2, 3, 4, 5}
0 Comments