python之集合

来源:互联网 发布:网络信号大师 编辑:程序博客网 时间:2024/06/04 22:28

集合的定义

PS.集合不能为空

##集合可以是普通的数字In [1]: s1 = {1,2,3}In [2]: type(s1)Out[2]: set##集合是一个无序的,不重复的数据组合In [3]: s2 = {1,2,3,2,3,4}In [4]: s2Out[4]: {1, 2, 3, 4}In [5]: type(s2)Out[5]: set##集合可以含有字符串In [6]: s3 = {1,2,3,'hello'}In [7]: type(s3)Out[7]: set##集合可以含有元组In [8]: s4 = {1,2,3,'hello',(1,2,3)}In [9]: type(s4)Out[9]: set##因为集合是无序的,所以集合不能含有列表In [10]: s5 = {1,2,3,'hello',(1,2,3),[1,2,3]}---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-10-b181079b4888> in <module>()----> 1 s5 = {1,2,3,'hello',(1,2,3),[1,2,3]}TypeError: unhashable type: 'list'

集合的应用

集合是一个无序的,不重复的数据组合

1)列表去重In [12]: set = {1,2,3,1,1,2,3,'hello'}In [13]: setOut[13]: {1, 2, 3, 'hello'}2)关系的测试

集合的关系

python中:

s1 = {1, 2, 3, 100}s2 = {1, 2, 'hello'}交集:print s1.intersection(s2)并集:print s1.union(s2)差集:print s1.difference(s2)print s2.difference(s1)对等差分:print s1.symmetric_difference(s2)##子集 list_1.issubset(list_2)##父集 list_1.issuperset(list_2)##有无交集 list_1.isdisjoint(list_2)

这里写图片描述

数学中:

s1 = {1,2,100}s2 = {1,2,3,'hello'}交集:print s1 & s2并集:print s1 | s2差集:print s1 - s2print s2 - s1对等差分:print s1 ^ s2

这里写图片描述

集合的添加

In [1]: s = {1,2,3,'hello'}##s.add()在集合中添加一项In [2]: s.add(23)In [3]: sOut[3]: {1, 2, 3, 23, 'hello'}##s.update()在集合中添加多项,可迭代In [4]: s.update(['world','1'])In [5]: sOut[5]: {1, 2, 3, 23, '1', 'hello', 'world'}

集合的删除

In [6]: sOut[6]: {1, 2, 3, 23, '1', 'hello', 'world'}##s.remove()删除集合中指定的元素In [7]: s.remove('1')In [8]: sOut[8]: {1, 2, 3, 23, 'hello', 'world'}##s.pop()随机删除集合中的元素,并返回删除的元素In [9]: s.pop()Out[9]: 1In [10]: sOut[10]: {2, 3, 23, 'hello', 'world'}

集合的其他操作

##len(s)显示集合的长度In [11]: len(s)Out[11]: 5In [12]: sOut[12]: {2, 3, 23, 'hello', 'world'}##判断元素是否属于集合In [13]: 2 in sOut[13]: TrueIn [14]: 1 in sOut[14]: False

集合的其他操作

##s.copy()集合的浅拷贝##s.clear()清空集合的所有元素In [15]: sOut[15]: {2, 3, 23, 'hello', 'world'}In [16]: s.clear()In [17]: sOut[17]: set()