python之集合

xiaoxiao2021-02-28  198

集合的定义

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]: s2 Out[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]: set Out[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 - s2 print s2 - s1 对等差分: print s1 ^ s2

集合的添加

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

集合的删除

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

集合的其他操作

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

集合的其他操作

##s.copy()集合的浅拷贝 ##s.clear()清空集合的所有元素 In [15]: s Out[15]: {2, 3, 23, 'hello', 'world'} In [16]: s.clear() In [17]: s Out[17]: set()
转载请注明原文地址: https://www.6miu.com/read-84301.html

最新回复(0)