集合类型 (python)

集合类型 (python)

在数学上,set称做由不一样的元素组成的集合,集合的成员称做集合元素。集合对象是一组无序排列可哈希值。 集合包含两种类型,可变集合(set)和不可变集合(frozenset)。python

1集合操做符

数学表示           python符号    python函数    
A ∈ B               in    
A ∉ B              not in    
A = B                ==
A ≠ B               !=      
A是B的严格子集        <       
A是B的子集           <=       issubset()
 ∩  交集             &       intersection()
 ∪  并集               |        union()
s - t 属于s不属于t    -       difference()
 △ 属于s或者t,但不一样时 ^       symmetric_difference()

2集合操做

2.1建立

>>> s = set('cheeseshope')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's'])
>>> t = frozenset('bookshop')
>>> t
frozenset(['b', 'h', 'k', 'o', 'p', 's'])

>>> type(s)
<type 'set'>
>>> type(t)
<type 'frozenset'>

>>> len(s)
6
>>> len(t)
6

2.2访问

>>> 'c' in s
True
>>> 'ch' in s
False
>>> 'c' not in t
True
>>> [i for i in s]
['c', 'e', 'h', 'o', 'p', 's']

2.3更新集合

>>> s = set('cheeseshope')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's'])
>>>          s.add('ph')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's', 'ph'])
>>> s.update('yahu')
>>> s
set(['a', 'c', 'e', 'h', 'o', 'p', 's', 'u', 'y', 'ph'])
>>> s.remove('ph')
>>> s
set(['a', 'c', 'e', 'h', 'o', 'p', 's', 'u', 'y'])
>>> s -= set('cookshop')
>>> s
set(['a', 'e', 'u', 'y'])

3内建函数

len(s)              s的长度
s.issubset(t)       s是t的子集
s.issuperset(t)     s是t得超集
s.union(t)          返回s和t的并集
s.intersection(t)   返回s和t的交集
s.difference(t)     返回新集合,是s得成员,但不是t的成员
s.symmetric_difference(t)   返回新集合,是s和t的成员,但不是共有的成员
s.copy()            浅拷贝

s.update(t)         将t放入s中,即s如今包含s和t
s.intersection_update(t)    s中的成员是s和t共有的元素
s.difference_update(t)      s中得成员属于s,但不属于t
s.symmetric_difference_update(t)    s中的成员为那些包含在s和t中,但不共有的元素
s.add(obj)          在s中添加obj对象
s.remove(obj)       在s中移除obj对象
s.discard(obj)      若是obj是s中的元素,删除该对象
s.pop()             删除集合s中得任意一个对象,并返回
s.clear()           删除s中得全部元素