1.元素与集合的关系
元素要么属于某个集合,要么不属于。
2.集合与集合的关系
假设两个集合a和b:
(1)A是否等于B,即两个集合的元素是否完全一样。
表达式:a==b
a!=b
>>> a=set('python')
>>> b=set('baidu')
>>> a
{'o', 'n', 'h', 'p', 'y', 't'}
>>> b
{'a', 'i', 'u', 'b', 'd'}
>>> a==b
False
>>> a!=b
True
(2)A是否是B的子集
表达式:A<B 或者A.issubset(B)
>>> a=set('python')
>>> b=set('baidu')
>>> a
{'o', 'n', 'h', 'p', 'y', 't'}
>>> b
{'a', 'i', 'u', 'b', 'd'}
>>> a<b
False
>>> a.issubset(b)
False
(3)A、B的并集,即A、B的所有元素
表达式:A|B 或者A.union(B)(注:结果是新生成的对象)
>>> a=set('python')
>>> b=set('baidu')
>>> c=a|b
>>> c
{'a', 'i', 'o', 'n', 'u', 'h', 'p', 'y', 't', 'b', 'd'}
>>> d=a.union(b)
>>> d
{'a', 'i', 'o', 'n', 'u', 'h', 'p', 'y', 't', 'b', 'd'}
(4)A、B的交集,即A、B所公有的元素(注:结果是新生成的对象)
表达式:A&B 或者A.intersection(B)
>>> s1=set("hello")
>>> s2=set("world")
>>> s1&s2
{'l', 'o'}
>>> s1.intersection(s2)
{'l', 'o'}
(5)A相对B的差(补),即A相对B不同的元素(注:结果是新生成的对象)
表达式:A-B 或者A.difference(B)
>>> s1=set("hello")
>>> s2=set("world")
>>> s1-s2
{'h', 'e'}
>>> s2-s1
{'w', 'd', 'r'}
>>> s1.difference(s2)
{'h', 'e'}
(6)A、B的对称差集,即除去A和B共同部分后剩余的元素集合(注:结果是新生成的对象)
表达式:A.symmetric_difference(B)
>>> s1=set("hello")
>>> s2=set("world")
>>> s1.symmetric_difference(s2)
{'w', 'e', 'd', 'r', 'h'}