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. """

A = set([1, 2, 3]) B = set([2, 3, 4]) print(B.intersection(A)) #输出{2, 3} """ 返回两个集合的交集到一个新的集合中 Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """

A = set([1, 2, 3]) B = set([2, 3, 4]) A.intersection_update(B) print(A) #输出{2, 3} """ 求一个集合与另一个集合的交集,并把结果返回当前集合 Update a set with the intersection of itself and another. """

A = set([1, 2, 3]) B = set([2, 3, 4]) print(A.isdisjoint(B)) #输出False A = set([1, 2, 3]) B = set([4, 5, 6]) print(A.isdisjoint(B)) #输出True """ 判断两个集合是否存在交集,有返回False,没有返回True Return True if two sets have a null intersection. """

A = set([1, 2, 3]) B = set([1, 2, 3, 4]) print(A.issuperset(B)) #输出False print(B.issuperset(A)) #输出True """ 判断当前集合是否是另一个集合父集合(另一个集合的所有元素都在当前集合中) Report whether this set contains another set. """

s = set([1, 2, 3]) a = s.pop() print(a) #输出1 print(s) #输出{2, 3} """ 随机删除一个元素,并返回那个元素,如果集合为空,将会抛出KeyError异常 Remove and return an arbitrary set element. Raises KeyError if the set is empty. """

s = set([1, 2, 3]) s.remove(2) print(s) #输出{1, 3} """ 从集合中删除一个元素,如果要删除的元素不在集合,将会抛出KeyError异常 Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """

A = set([1, 2, 3]) B = set([2, 3, 4, 5]) print(A.symmetric_difference(B)) #输出{1, 4, 5} print(B.symmetric_difference(A)) #输出{1, 4, 5} """ 返回两个集合的对称差集到一个新的集合 Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """

A = set([1, 2, 3]) B = set([2, 3, 4, 5]) A.symmetric_difference_update(B) print(A) #输出{1, 4, 5} """ 更新当前集合为与另外一个集合的对称差集 Update a set with the symmetric difference of itself and another. """

A = set([1, 2, 3]) B = set([2, 3, 4, 5]) print(A.union(B)) #输出{1, 2, 3, 4, 5} print(B.union(A)) #输出{1, 2, 3, 4, 5} """ 返回与另一个集合的并集为一个新的集合 Return the union of sets as a new set. (i.e. all elements that are in either set.) """

A = set([1, 2, 3]) B = set([2, 3, 4, 5]) A.update(B) print(A) #输出{1, 2, 3, 4, 5} """ 更新当前集合为与另一个集合的并集 Update a set with the union of itself and others. """
2.collections
collections是对Python现有的数据类型的补充,在使用collections中的对象要先导入import collections模块
2.1Counter--计数器
计数器是对字典的补充,继承自字典,除了具有字典的所有方法,还有很多扩展功能。
定义Counter对象
Counter接受一个序列对象,如list、tuple、str等,返回以字典形式(按照出现次数倒序)
import collections c = collections.Counter("asfsdfsdfgsdgf") print(c) c1 = collections.Counter(['tom', 'jack', 'tony', 'jack']) print(c1) ''' 输出结果 Counter({'s': 4, 'f': 4, 'd': 3, 'g': 2, 'a': 1}) Counter({'jack': 2, 'tom': 1, 'tony': 1}) '''
2.2Counter常用方法
#python3.x dir(collections.Counter()) #['__add__', '__and__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__le__', '__len__', '__lt__', '__missing__', '__module__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__weakref__', '_keep_positive', 'clear', 'copy', 'elements', 'fromkeys', 'get', 'items', 'keys', 'most_common', 'pop', 'popitem', 'setdefault', 'subtract', 'update', 'values']

c = collections.Counter("dsadfasfasfasf") print(c.most_common(3)) print(c.most_common(2)) ''' 输出 [('s', 4), ('a', 4), ('f', 4)] [('s', 4), ('a', 4)] '''

c = collections.Counter("safasfsadasdas") print(c.elements()) print(list(c.elements())) ''' 输出 <itertools.chain object at 0x0000000005040C88> ['s', 's', 's', 's', 's', 'a', 'a', 'a', 'a', 'a', 'f', 'f', 'd', 'd'] 注意:返回的是一个迭代器对象,可以通过内置方法将其转化为列表对象,也可以通过for in进行遍历 '''

c = collections.Counter(['tom', 'jack', 'tony', 'jack']) c.update('peter') print(c) # 注意参数是一个序列对象,如果传的是一个字符串,字符串的每一个字符都会被当成一个元素 c = collections.Counter(['tom', 'jack', 'tony', 'jack']) c.update(['tom']) print(c) ''' 输出 Counter({'jack': 2, 'e': 2, 'tom': 1, 'tony': 1, 'p': 1, 't': 1, 'r': 1}) Counter({'tom': 2, 'jack': 2, 'tony': 1}) '''

c = collections.Counter(['tom', 'jack', 'tony', 'jack']) c.subtract(['tom']) print(c) c.subtract(['tom']) print(c) ''' 输出 Counter({'jack': 2, 'tony': 1, 'tom': 0}) Counter({'jack': 2, 'tony': 1, 'tom': -1}) 注意: 注意:如果成员已经不存在了或者说为0了,计数器会继续递减,也就是说计数器有0和负数的概念的,但是使用elements显示的时候却没有该成员,如果计时器是0或者负数能说明这个成员出现过而已,另外如果为负数的时候,添加成员,成员不会真的添加到elements显示的成员中,直到计数器大于0为止 '''
3.OrderedDict 有序字典
我们都知道字典是无序的,OrderedDict 是对字典的扩展,使其有序,并根据添加顺序进行排序
c = collections.OrderedDict()
我们也可以通过一个现有的字典进行初始化有序字典
old_dict = {'k1':'1', 'k2':'2', 'k3':'3'} new_dict = collections.OrderedDict(old_dict) print(new_dict) #输出OrderedDict([('k1', '1'), ('k2', '2'), ('k3', '3')])
有序字典常用方法
old_dict = {'k1':'1', 'k2':'2', 'k3':'3'} new_dict = collections.OrderedDict(old_dict) dir(new_dict) #['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'move_to_end', 'pop', 'popitem', 'setdefault', 'update', 'values']

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) dic.clear() print(dic) ''' 输出OrderedDict() '''

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) print(dic.keys()) ''' 输出:odict_keys(['a', 'b', 'c']) '''

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) print(dic.values()) #输出odict_values([1, 2, 3])

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) print(dic.items()) #输出odict_items([('a', 1), ('b', 2), ('c', 3)])

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) print(dic.pop('b')) #输出2 print(dic) #输出OrderedDict([('a', 1), ('c', 3)]) print(dic.pop('d', 10)) #输出10 ''' 删除指定key的元素,并返回key所对应的值 k:要删除的元素的key d:如果key不存在返回的默认值 '''

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) print(dic.popitem()) #输出('c', 3) """ 删除末尾的元素,并返回删除的元素的key和value """

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 设置某个键的默认值,使用get方法如果该键不存在返回的值 """ pass

def move_to_end(self, *args, **kwargs): # real signature unknown """ 移动一个元素到字典的末尾,如果该元素不存在这回抛出KeyError异常 同原生字典,不同的是有序和无序 """

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3}) dic.move_to_end('b') print(dic) #输出OrderedDict([('a', 1), ('c', 3), ('b', 2)]) """ 移动一个元素到字典的末尾,如果该元素不存在这回抛出KeyError异常 """

dic = collections.defaultdict(list) #定义的时候需要指定默认的数据类型,这里指定的是列表类型 dic['k1'].append('a') #尽管当前key还没有值,但是它默认已经是列表类型,所以直接可以用列表的append方法 print(dic) #输出defaultdict(<class 'list'>, {'k1': ['a']}) """ defaultdict是对字典的扩展,它默认个给字典的值设置了一种默认的数据类型,其他的均与原生字典一样 """
4.namedtuple可命名元组
可命名元组是元组的扩展,包含所有元组的方法的同时可以给每个元组的元素命名,访问时候也不需要再通过索引进行访问,直接通过元素名即可访问
MytupleClass = collections.namedtuple('MytupleClass',['x', 'y', 'z']) mytuple = MytupleClass(11, 22, 33) print(mytuple.x) #11 print(mytuple.y) #22 print(mytuple.z) #33
5.deque双向队列
deque是一个线程安全的双向队列,类似列表,不同的是,deque是线程安全,并且是双向的也就是两边都可以进出
5.1定义双向队列
d = collections.deque()
5.2常用方法
d = collections.deque() dir(d) #['__add__', '__bool__', '__class__', '__contains__', '__copy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'appendleft', 'clear', 'copy', 'count', 'extend', 'extendleft', 'index', 'insert', 'maxlen', 'pop', 'popleft', 'remove', 'reverse', 'rotate']

d = collections.deque([1, 2, 3]) d.append(4) print(d) #输出deque([1, 2, 3, 4]) """ 从右边追加一个元素到队列的末尾 """

d = collections.deque([1, 2, 3]) d.appendleft(4) print(d) #输出deque([4, 1, 2, 3]) """ 从左边追加一个元素到队列的末尾 """

d = collections.deque([1, 2, 3]) d.clear() print(d) #deque([]) """ 清空队列 """

d = collections.deque([1, 2, 3, 1]) print(d.count(1)) #输出2

d = collections.deque([1, 2, 3]) d.extend([4, 5]) print(d) #输出deque([1, 2, 3, 4, 5])

d = collections.deque([1, 2, 3]) d.extendleft([4, 6]) print(d) #输出deque([6, 4, 1, 2, 3])

def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ 查找元素是否存在,如果不存在将会抛出ValueError异常,如果存在返回第一找到的索引位置 value:要查找的元素 start:查找的开始所以你能 stop:查找的结束索引 """ return 0 #使用方法同列表,需要说明虽然是双向队列,但是索引还是从左到右编码的

d = collections.deque([1, 2, 3]) d.insert(0, 4) print(d) #deque([4, 1, 2, 3])

d = collections.deque([1, 2, 3]) print(d.pop()) #输出3 print(d) #输出deque([1, 2])

d = collections.deque([1, 2, 3]) print(d.popleft()) #输出1 print(d) #输出deque([2, 3])

d = collections.deque([1, 2, 3, 2]) d.remove(2) print(d) #输出deque([1, 3, 2])

d = collections.deque([1, 2, 3]) d.reverse() print(d) #输出deque([3, 2, 1])

d = collections.deque([1, 2, 3, 4, 5]) d.rotate(2) print(d) """ 队列旋转,默认移动1位 输出deque([4, 5, 1, 2, 3]) 双向队列的旋转可以理解为,双向队列的首位是相连的环,旋转就是元素移动了多少个位置,如下图所示,或者说从左边取出元素追加到右边,追加了多少次 """