标签:分享图片 删除元素 size 添加元素 super 并集 rem union contains
1.set(集合)
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
集合和我们数学中集合的概念是一样的,也有交集、并集、差集、对称差集等概念。
1.1定义集合需要提供一个列表作为参数,也可以不传参数创建一个空集合
>>> s = set([1, 2, 2, 3]) >>> s {1, 2, 3} # 可以看到在创建集合对象对过程中已经为我们把重复的元素剔除掉了 >>> s = set() set()
1.2set常用方法
#python3.x dir(set) #[‘__and__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__iand__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__ior__‘, ‘__isub__‘, ‘__iter__‘, ‘__ixor__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__or__‘, ‘__rand__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__ror__‘, ‘__rsub__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__xor__‘, ‘add‘, ‘clear‘, ‘copy‘, ‘difference‘, ‘difference_update‘, ‘discard‘, ‘intersection‘, ‘intersection_update‘, ‘isdisjoint‘, ‘issubset‘, ‘issuperset‘, ‘pop‘, ‘remove‘, ‘symmetric_difference‘, ‘symmetric_difference_update‘, ‘union‘, ‘update‘]
s = set([1, 2, 3]) s.add(4) print(s) """ 添加一个新的元素,如果该元素已经存在,将不会有任何操作 Add an element to a set. This has no effect if the element is already present. """ #输出{1, 2, 3, 4}
s = set([1, 2, 3]) s.clear() print(s) """ 删除所有元素 return:None Remove all elements from this set. """ #输出set()
A = set([1, 2, 3]) B = set([2, 3, 4]) print(A.difference(B)) """ 求当前差集和另一个集合的差集 return:差集 Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ #输出{1}
A = set([1, 2, 3]) B = set([2, 3, 4]) A.difference_update(B) print(A) """ 从当前集合中删除所有另一个集合中存在的元素 其实就相当于将difference返回的值又付给了当前集合 可以理解为A = A - B,或者A -= B Remove all elements of another set from this set. """ #输出集合A结果为{1}
A = set([1, 2, 3]) A.discard(2) print(A) #输出{1, 3} A.discard(4) print(A) #输出{1, 3} """ 如果一个集合中存在这个元素则删除,否则什么都不做 Remove an element from a set if it is a member. If the element is not a member, do nothing. """
python基础(6)---set、collections介绍
标签:分享图片 删除元素 size 添加元素 super 并集 rem union contains
原文地址:http://www.cnblogs.com/caoj/p/7865815.html