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}