1 集合
1.1 集合的特征
1.2 集合的定义
>>> s=set('hello')
>>> s
set(['h', 'e', 'l', 'o'])
>>>
>>> str_s=set(['alex','alex','sb'])
>>> print str_s
set(['sb', 'alex'])
>>> f=frozenset(s)
>>> f
frozenset(['h', 'e', 'l', 'o'])
>>>
1.3 集合的内置方法
>>> name = ['xixi','sisi','jiji','lili','lili']
>>> s= set(name)
>>> s
{'lili', 'xixi', 'sisi', 'jiji'}
>>> s= set(name)
>>> s
{'lili', 'xixi', 'sisi', 'jiji'}
>>> name=list(s)
>>> name
['lili', 'xixi', 'sisi', 'jiji']
>>>
#add方法
>>> s.add(3)
>>> s
set(['h', 3, 'e', 'l', 'o'])
>>>
#clear方法
>>> s.clear()
>>> s
set([])
>>>
#copy方法
>>> s2=s.copy()
>>> s2
set([])
>>>
#pop 随机删除
>>> s={1,2,3,4,5,6}
>>> s
set([1, 2, 3, 4, 5, 6])
>>> s.pop() #返回值为删除的元素
1
>>> s
set([2, 3, 4, 5, 6])
>>>
#remove 删除指定元素,元素不存在时会报错
>>> s.remove(4)
>>> s
set([2, 3, 5, 6])
>>>
#discard 删除指定元素,元素不存在时不报错
>>> s.discard(5)
>>> s
set([2, 3, 6])
>>> s.discard('s')
>>> s
set([2, 3, 6])
1.4 集合的交集、并集、差集运算
>>> class_1=['zhangsan','lisi','xixi']
>>> class_2=['lili','lucy','xixi','mimi']
#低级写法
>>> class_12=[ ]
>>> for name in class_1:
... if name in class_2:
... class_12.append(name)
... print class_12
#set写法
>>> c1=set(class_1) #转成集合,去重
>>> c1
set(['lisi', 'zhangsan', 'xixi'])
>>> c2=set(class_2)
>>> c2
set(['mimi', 'xixi', 'lili', 'lucy'])
>>> print c1.intersection(c2) #求交集
set(['xixi'])
>>> print c1&c2 #求交集
set(['xixi'])
>>>
>>> print c1.union(c2) #求并集
set(['lisi', 'mimi', 'xixi', 'lili', 'zhangsan', 'lucy'])
>>> print c1|c2 #求并集
set(['lisi', 'mimi', 'xixi', 'lili', 'zhangsan', 'lucy'])
>>>
>>> print c1.difference(c2) #求c1的差集
set(['lisi', 'zhangsan'])
>>> print c2.difference(c1) #求c2的差集
set(['mimi', 'lili', 'lucy'])
>>>
>>> class1=['lili','lucy','mimi']
>>> class2=['cici','sisi','kiki','mimi']
>>> c1=set(class1)
>>> c1
{'lili', 'lucy', 'mimi'}
>>> c2=set(class2)
>>> c2
{'kiki', 'mimi', 'sisi', 'cici'}
>>> c1.symmetric_difference(c2) #求交叉补集
{'lili', 'lucy', 'kiki', 'sisi', 'cici'}
>>> c=c1^c2 #求交叉补集
>>> c
{'lili', 'lucy', 'kiki', 'sisi', 'cici'}
>>>
1.5 set其它的内置函数
- isdisjoint 判断是否有 交集,无交集返回true,有交集返回false
>>> c1.isdisjoint(c2)
False
>>>
- issubset 判断是否是子集,是——返回true,否——返回false
>>> c1.issubset(c2)
False
>>>
- issuperset 判断是否是父集,是——返回true,否——返回false
>>> c1.issuperset(c2)
False
>>>
>>> c1
{'lili', 'lucy', 'mimi'}
>>> c2=set(class2)
>>> c2
{'kiki', 'mimi', 'sisi', 'cici'}
>>> c1.update(c2)
>>> c1
{'lucy', 'kiki', 'lili', 'mimi', 'sisi', 'cici'}
>>>
网友评论