学习Python中的集合
创建集合
使用工厂方法 set()和 frozenset():
>>> s = set('cheeseshop')>>> sset(['c', 'e', 'h', 'o', 'p', 's'])>>> t = frozenset('bookshop')>>> tfrozenset(['b', 'h', 'k', 'o', 'p', 's'])>>> type(s)<type 'set'>>>> type(t)<type 'frozenset'> |
更新集合
用各种集合内建的方法和操作符添加和删除集合的成员:
>>> s.add('z')>>> sset(['c', 'e', 'h', 'o', 'p', 's', 'z'])>>> s.update('pypi')>>> sset(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y', 'z'])>>> s.remove('z')>>> sset(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])>>> s -= set('pypi')>>> sset(['c', 'e', 'h', 'o', 's']) |
删除集合
del set() |
成员关系 (in, not in)
>>> s = set('cheeseshop')>>> t = frozenset('bookshop')>>> 'k' in sFalse>>> 'k' in tTrue>>> 'c' not in tTrue |
集合等价/不等价
>>> s == tFalse>>> s != tTrue>>> u = frozenset(s)>>> s == uTrue>>> set('posh') == set('shop')True |
差补/相对补集( – )
两个集合(s 和t)的差补或相对补集是指一个集合C,该集合中的元素,只属于集合s,而不属于集合t。差符号有一个等价的方法,difference().
>>> s - tset(['c', 'e']) |
对称差分( ^ ):对称差分是集合的XOR
利用集合去除列表中的重复元素
>>> xs = [5, 8, 5, 1, 1, 4, 2, 4, 3, 2]>>> set(xs)set([1, 2, 3, 4, 5, 8])>>> sorted(set(xs), key=xs.index) # 保持原来的顺序[5, 8, 1, 4, 2, 3] |
有需要的话可以关注我的微信公众号,会第一时间接收最新的知识。

浙公网安备 33010602011771号