集合本质上具有基本的数学特性。集合不能包含重复项,所以可以用来去重,如list(set([1,1,2,2]))
>>> x = set('abcde')
>>> y = set('bdxyz')
>>> x
{'e', 'b', 'c', 'd', 'a'}
>>> y
{'z', 'b', 'x', 'd', 'y'}
>>> x-y # difference,x去掉y中同样有的
{'c', 'a', 'e'}
>>> x|y # union 并集
{'e', 'z', 'b', 'x', 'c', 'd', 'y', 'a'}
>>> x&y # Intersection 交集
{'d', 'b'}
>>> x^y # Symmertric difference异或
{'c', 'y', 'z', 'a', 'e', 'x'}
>>> x>y, x<y # superset,subset包含关系
(False, False)
>>> z = x.intersection(y) 交集
>>> z
{'d', 'b'}
>>> z.add('cute') #添加
>>> z
{'d', 'b', 'cute'}
>>> z.update(set(['o','p'])) #扩展
>>> z
{'d', 'o', 'b', 'cute', 'p'}
>>> z.remove('cute') #删除
>>> z
{'d', 'o', 'b', 'p'}
>>> z = {'d','b','cute'}
>>> z | ['d','q'] # 要求都为set
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
z | ['d','q']
TypeError: unsupported operand type(s) for |: 'set' and 'list'
>>> z.union(['d','q']) # 方法允许任何可迭代对象
{'d', 'q', 'b', 'cute'}
在python中,{}创建的是一个空字典,空的集合必须通过内置函数set来创建: s = set()
集合只能包含不可变的(即散列的)对象类型,因此列表和字典不能嵌入到集合中,集合本身是可变的,不能直接嵌入到其他集合中,如果有需要可以创建frozenset
集合解析:
>>> {x**2 for x in [1,2,3,4]}
{16, 1, 4, 9}
Learning Python, Fourth Edition, by Mark Lutz.