Python 集合
集合: 元素唯一性, 无序性.即其不存在索引,元素不重复. 集合是unhashable的.
定义一个集合.
>>> a = {1,2,3}
>>> type(a)
<class 'set'>
定义一个空集合.
>>> b = set()
>>> b
set()
集合的一些运算符.
&: 交集. |: 并集. -: 差集. <: 包含关系. >: 包含关系. ^: 与非集.(并集减去交集的结果)
实际操作一波.
>>> a,b = {1,2,3,4},{4,5,6}
>>> a & b
{4}
>>> a | b
{1,2,3,4,5,6}
>>> a - b
{1, 2, 3}
>>> a ^ b
{1, 2, 3, 5, 6}
>>> b = {1,2,3}
>>> a > b
True
>>> a < b
False
集合的一些方法,更具体的解释和方法可使用help(obj),dir(obj)或者官方文档查看.
add(): 添加一个元素到集合中. clear(): 清空集合内容. copy(): 将一个集合的内容复制到集合中(浅). pop(): 随机弹出一个元素,并返回该元素的值. update(): 添加一个集合对象到集合中. remove(): 选择移除一个元素. isdisjoint(): 与目标对象(list,tuple,set)比较是否相交,相交就返回False,不相交(disjoint)就返回True. issubset(): 与目标对象比较是否为其子集(subset),如果是就返回True,不是就返回False. issuperset(): 与目标对象比较是否为其父集(superset),如果是就返回True,不是就返回False.
SHOW TIME.
>>> dir(a)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> a,b = set(),set()
>>> a.add(1)
>>> b.update({1,2,3})
>>> print(a,b)
{1} {1,2,3}
>>> c = b.copy()
>>> c
{1, 2, 3}
>>> b.pop()
1
>>> b.remove(3)
>>> b
{2}
>>> b.clear()
>>> b
set()
>>> b.update({1,2,3})
>>> a
{1}
>>> a.isdisjoint(b)
False
>>> a.issubset(b)
True
>>> a.issuperset(b)
False