set 是一个无序不重复的元素集,集合跟字典是无序的,不支持索引
创建集合:
第一种方式:通过{ }创建
>>> num={1,2,3,4,3,3,1}>>> num{ 1, 2, 3, 4}>>> type(num)
第二种方式:通过set()
>>> li=set(['aaa','bbb','aaa'])>>> li{ 'aaa', 'bbb'}
可以去除列表里的重复项但不能保证顺序:
>>> num=[4,3,2,1,2,2]
>>> num=list(set(num))>>> num[1, 2, 3, 4]
class set(object): def add(self, *args, **kwargs): #添加,把传入的元素作为一个整个添加进去 >>> st.add('python') >>> st { 'd', 'f', 'python', 'a', 'b', 'c'} def update(self, *args, **kwargs): # 更新,把传入的元素拆分然后传入集合 """ >>> s1=set('boy') >>> s1 {'b', 'y', 'o'} >>> s1.update('python') >>> s1 {'t', 'y', 'p', 'n', 'h', 'b', 'o'} """ pass def clear(self, *args, **kwargs): # 清空 >>> st.clear() >>> st set() pass def copy(self, *args, **kwargs): # 拷贝 def difference(self, *args, **kwargs): #差集。在s1集合,不在s2集合的,操作后可以输出返回值 >>> s1=set(['aaa','bbb']) >>> s2=set(['bbb','ccc']) >>> s1.difference(s2) { 'aaa'} def difference_update(self, *args, **kwargs): #将s1更新为s1-s2的差集。没有返回值 >>> s1 { 'aaa', 'bbb'} >>> s2 { 'bbb', 'ccc'} >>> s1.difference_update(s2) >>> s1 { 'aaa'} >>> s2 { 'bbb', 'ccc'} def discard(self, *args, **kwargs): # 删除 def remove(self, *args, **kwargs): # 删除 #set.remove(obj)和set.discard(obj)的区别在于,当obj存在于set中时,都将其删除;但当obj不存在于set中时,remove()会报错,discard()不会。 def pop(self, *args, **kwargs): # 随机删除 >>> a=set('abcd') >>> a.pop() 'b' >>> a.pop() 'd' def intersection(self, *args, **kwargs): # 交集 s1 & s2 >>> s1=set(['aaa','bbb']) >>> s2=set(['bbb','ccc']) >>> d=s1.intersection(s2) >>> print(d) { 'bbb'} def intersection_update(self, *args, **kwargs): # 交集 s1更新为这个值 def isdisjoint(self, *args, **kwargs): # 没有交集 >>> s1.isdisjoint(s2) False def issubset(self, *args, **kwargs): # s1的每一个元素都在s2中 >>> s1=set('abc') >>> s2=set('abcdef') >>> s1.issubset(s2) True def issuperset(self, *args, **kwargs): # s2的每一个元素都在s1中 >>> s1.issuperset(s2) False def symmetric_difference(self, *args, **kwargs): # s1,s2的对称差,有返回值 >>> s1=set(['aaa','bbb']) >>> s2=set(['bbb','ccc']) >>> d=s1.symmetric_difference(s2) >>> print(d) { 'ccc', 'aaa'} def symmetric_difference_update(self, *args, **kwargs): # s1更新为s1,s2的对称差,没有返回值 >>> s1=set(['aaa','bbb']) >>> s2=set(['bbb','ccc']) >>> s1.symmetric_difference_update(s2) >>> s1 { 'aaa', 'ccc'} def union(self, *args, **kwargs): # 并集 s1 | s2
还有一种不可变的集合:frozenset
>>> s = frozenset([1,2,3,4])
>>> s.add(0)Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'frozenset' object has no attribute 'add'