zoukankan      html  css  js  c++  java
  • python基础(6)---set、collections介绍

    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}
    add 添加元素
    s = set([1, 2, 3])
    s.clear()
    print(s)
    
    """ 
             删除所有元素
             return:None
             Remove all elements from this set. 
    """
    
    #输出set()
    clear 清空集合
    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}
    difference 差集
    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}
    difference_update 差集
    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.
    """
    discard 从集合中删除元素
    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.)
    """
    intersection 交集
    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. 
    """
    intersection_update 交集
    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. 
    """
    isdisjoint 判断是否有交集(注意:这里是没有交集返回True,有交集返回False,有点别扭,但不要搞反了
    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. 
    """
    issuperset 判断当前集合是否是另一个集合的父集合(包括等于)
    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.
    """
    pop 随机删除元素,并返回删除的元素
    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.
    """
    remove 删除一个元素
    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.)
    """
    symmetric_difference 返回两个集合的对称差集
    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. 
    """
    symmetric_difference_update 当前集合更新为与另一个集合的对称差集
    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.)
    """
    union 返回与另一个集合的并集为一个新的集合
    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. 
    """
    update 更新当前集合为与另一个集合的并集

    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)]
    '''
    most_common——返回前几个的元素和对应出现的次数(按照出现次数的倒序排列)
    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进行遍历
    '''
    elements——返回所有元素,迭代器对象
    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})
    '''
    update——添加一个新的成员,如果存在计数器的值进行累加,如果不存在将新建一个成员
    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为止
    '''
    subtract——减去一个成员,计数器减1

    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()
    '''
    clear——清空字典
    dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
    print(dic.keys())
    
    '''
    输出:odict_keys(['a', 'b', 'c'])
    '''
    keys——返回所有key组成的迭代对象
    dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
    print(dic.values())
    
    #输出odict_values([1, 2, 3])
    values——返回所有value组成的迭代对象
    dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
    print(dic.items())
    
    #输出odict_items([('a', 1), ('b', 2), ('c', 3)])
    items——返回key和value组成的迭代对象
    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不存在返回的默认值
    '''
    pop——删除指定key的元素
    dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
    print(dic.popitem())    #输出('c', 3)
    
    
    """
    删除末尾的元素,并返回删除的元素的key和value
    """
    popitem——删除末尾的元素
    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
    """ 
    设置某个键的默认值,使用get方法如果该键不存在返回的值
    """
             pass
    setdefault——设置默认值
    def move_to_end(self, *args, **kwargs): # real signature unknown
             """
             移动一个元素到字典的末尾,如果该元素不存在这回抛出KeyError异常
             同原生字典,不同的是有序和无序
              """
    update——将另一个字典更新到当前字典
    dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
    dic.move_to_end('b')
    print(dic)    #输出OrderedDict([('a', 1), ('c', 3), ('b', 2)])
    
    
    """
    移动一个元素到字典的末尾,如果该元素不存在这回抛出KeyError异常
    
    """
    move_to_end——将一个存在的元素移动到字典的末尾
    dic = collections.defaultdict(list)  #定义的时候需要指定默认的数据类型,这里指定的是列表类型
    dic['k1'].append('a')  #尽管当前key还没有值,但是它默认已经是列表类型,所以直接可以用列表的append方法
    print(dic)  #输出defaultdict(<class 'list'>, {'k1': ['a']})
    
    """
     defaultdict是对字典的扩展,它默认个给字典的值设置了一种默认的数据类型,其他的均与原生字典一样
    """
    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])
    
    
    """
    从右边追加一个元素到队列的末尾
    """
    append——从右边追加一个元素到队列的末尾
    d = collections.deque([1, 2, 3])
    d.appendleft(4)
    print(d)    #输出deque([4, 1, 2, 3])
    
    """
    从左边追加一个元素到队列的末尾
    """
    appendleft——从左边追加一个元素到队列的末尾
    d = collections.deque([1, 2, 3])
    d.clear()
    print(d)    #deque([])
    
    """
    清空队列
    """
    clear——清空队列
    d = collections.deque([1, 2, 3, 1])
    print(d.count(1))   #输出2
    count——返回某个成员重复出现的次数
    d = collections.deque([1, 2, 3])
    d.extend([4, 5])
    print(d)    #输出deque([1, 2, 3, 4, 5])
    extend——从队列右边扩展一个可迭代的对象
    d = collections.deque([1, 2, 3])
    d.extendleft([4, 6])
    print(d)    #输出deque([6, 4, 1, 2, 3])
    extendleft——从队列左侧扩展一个可迭代的对象
    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
             """
             查找元素是否存在,如果不存在将会抛出ValueError异常,如果存在返回第一找到的索引位置
             value:要查找的元素
             start:查找的开始所以你能
             stop:查找的结束索引
             """
             return 0
    
    
    #使用方法同列表,需要说明虽然是双向队列,但是索引还是从左到右编码的
    index——查找并返回索引
    d = collections.deque([1, 2, 3])
    d.insert(0, 4)
    print(d)    #deque([4, 1, 2, 3])
    insert——插入索引
    d = collections.deque([1, 2, 3])
    print(d.pop())    #输出3
    print(d)    #输出deque([1, 2])
    pop——从队列右侧末尾删除一个元素,并返回该元素
    d = collections.deque([1, 2, 3])
    print(d.popleft())    #输出1
    print(d)    #输出deque([2, 3])
    popleft——从队列左侧删除一个元素,并返回该元素
    d = collections.deque([1, 2, 3, 2])
    d.remove(2)
    print(d)    #输出deque([1, 3, 2])
    remove——删除一个元素
    d = collections.deque([1, 2, 3])
    d.reverse()
    print(d)    #输出deque([3, 2, 1])
    reverse——翻转队列
    d = collections.deque([1, 2, 3, 4, 5])
    d.rotate(2)
    print(d)
    
    """
    队列旋转,默认移动1位
    输出deque([4, 5, 1, 2, 3])
     双向队列的旋转可以理解为,双向队列的首位是相连的环,旋转就是元素移动了多少个位置,如下图所示,或者说从左边取出元素追加到右边,追加了多少次
    
    """
    rotate——旋转队列
  • 相关阅读:
    mac与phy怎样实现网络自适应
    POJ 3304 Segments(计算几何:直线与线段相交)
    iOS类目
    MFC中改变控件的大小和位置(zz)
    Delphi中根据分类数据生成树形结构的最优方法
    Delphi下EasyGrid使用体会
    Delphi中Messagedlg用法
    Delphi获取其它进程窗口句柄的3种方法
    delphi获取一个窗口的所有子窗口(包括嵌套)
    关于获取其它程序窗口编辑框内容解决思路
  • 原文地址:https://www.cnblogs.com/caoj/p/7865815.html
Copyright © 2011-2022 走看看