学习Python中的集合

创建集合

使用工厂方法 set()和 frozenset():

>>> s =  set ( 'cheeseshop' )
>>> 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' >

更新集合

用各种集合内建的方法和操作符添加和删除集合的成员:

>>> s.add( 'z' )
>>> s
set ([ 'c' , 'e' , 'h' , 'o' , 'p' , 's' , 'z' ])
>>> s.update( 'pypi' )
>>> s
set ([ 'c' , 'e' , 'i' , 'h' , 'o' , 'p' , 's' , 'y' , 'z' ])
>>> s.remove( 'z' )
>>> s
set ([ 'c' , 'e' , 'i' , 'h' , 'o' , 'p' , 's' , 'y' ])
>>> s - =  set ( 'pypi' )
>>> s
set ([ 'c' , 'e' , 'h' , 'o' , 's' ])

删除集合

del  set()

成员关系 (in, not in)

>>> s =  set ( 'cheeseshop' )
>>> t =  frozenset ( 'bookshop' )
>>> 'k'  in  s
False
>>> 'k'  in  t
True
>>> 'c'  not  in  t
True

集合等价/不等价

>>> s = =  t
False
>>> s ! =  t
True
>>> u =  frozenset (s)
>>> s = =  u
True
>>> set ( 'posh' ) = =  set ( 'shop' )
True

差补/相对补集( – )

两个集合(s 和t)的差补或相对补集是指一个集合C,该集合中的元素,只属于集合s,而不属于集合t。差符号有一个等价的方法,difference().

>>> s -  t
set ([ '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 ]

猜你喜欢

转载自www.cnblogs.com/liudemeng/p/9137955.html