python 入坑路3

集合操作

  

#集合创建

>>> s=set([1,2,3,4,5])
>>> s
{1, 2, 3, 4, 5}
>>> t=set("hello world")
>>> t
{'h', 'r', 'e', 'o', ' ', 'w', 'd', 'l'}
>>> s=set([1,2,3,4,5])
>>> s
{1, 2, 3, 4, 5}
>>> t=set("hello world")
>>> t
{'h', 'r', 'e', 'o', ' ', 'w', 'd', 'l'}

#集合 ,add ,update方法

>>> t.add("python")
>>> t
{'python', 'h', 'r', 'e', 'o', ' ', 'w', 'd', 'l'}  #python 作为一个整理添加到集合中

>>> t.add("python")
>>> t
{'python', 'h', 'r', 'e', 'o', ' ', 'w', 'd', 'l'} #python 被拆分成字母,添加到集合中

# 使用remove 方法删除其中一项
>>> t
{'h', 'r', 't', 'e', 'p', 'o', ' ', 'y', 'n', 'w', 'd', 'l'}
>>> t.remove("h","t")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (2 given)
>>> t.remove("h")
>>> t
{'r', 't', 'e', 'p', 'o', ' ', 'y', 'n', 'w', 'd', 'l'}

集合常用方法,

1,合集

>>> a=set("abc")
>>> b=set("cdef")
>>> a
{'c', 'b', 'a'}
>>> b
{'d', 'c', 'f', 'e'}
>>> c=a-b
>>> c
{'b', 'a'}
>>>

 

2,交集

>>> c=a&b
>>> c
{'c'}
>>>

 

3,差集

>>> a=set("abc")
>>> b=set("cdef")
>>> a
{'c', 'b', 'a'}
>>> b
{'d', 'c', 'f', 'e'}
>>> c=a-b
>>> c
{'b', 'a'}
>>>

 其它方法参考下图

len(s)  
set 的长度  
  
x in s  
测试 x 是否是 s 的成员  
  
x not in s  
测试 x 是否不是 s 的成员  
  
s.issubset(t)  
s <= t  
测试是否 s 中的每一个元素都在 t 中  
  
s.issuperset(t)  
s >= t  
测试是否 t 中的每一个元素都在 s 中  
  
s.union(t)  
s | t  
返回一个新的 set 包含 s 和 t 中的每一个元素  
  
s.intersection(t)  
s & t  
返回一个新的 set 包含 s 和 t 中的公共元素  
  
s.difference(t)  
s - t  
返回一个新的 set 包含 s 中有但是 t 中没有的元素  
  
s.symmetric_difference(t)  
s ^ t  
返回一个新的 set 包含 s 和 t 中不重复的元素  
  
s.copy()  
返回 set “s”的一个浅复制  

 

posted @ 2017-12-24 12:17  东郭仔  阅读(173)  评论(0)    收藏  举报