Python之第二十八天的努力--collections模块

01 collections模块

  1. namedtuple() 命名元组

    # namedtuple() 命名元组
    Rectangle = collections.namedtuple(‘Rectangle_class‘,[‘length‘,‘width‘])
    #
    r = Rectangle(10,5)
    # 通过属性访问元组的元素
    print(r.length)         # 10
    print(r.width)          # 5
  2. defautldict() 默认值字典

    # defautldict()  默认值字典
    # 创建一个字典的方法:
    # 1.直接创建
    # dic = {‘name‘:‘zs‘,‘age‘:18}
    # 2.
    # dic = dict([(‘name‘,‘zs‘),(‘age‘,18)])
    # 3.
    # dic = {k:v for k,v in [(1,2),(3,4)]}
    
    #
    dic = collections.defaultdict(int,name=‘zs‘,age=18)
    print(dic[‘name‘])          # zs
    print(dic[‘age‘])           # 18
    print(dic[‘aaa‘])           # 0 ---> 和int对应,且把{‘aaa‘:0}添加进来。
    print(dic)                  # defaultdict(<class ‘int‘>, {‘name‘: ‘zs‘, ‘age‘: 18, ‘aaa‘: 0})
    
    # 自定义函数充当第一个参数:
    # 要求,不能有参数
    def func():
        return ‘hello‘
    
    dic = collections.defaultdict(func,name=‘zs‘,age=18)
    print(dic[‘aaa‘])               # hello
    print(dic)                      # defaultdict(<function func at 0x02E517C8>, {‘name‘: ‘zs‘, ‘age‘: 18, ‘aaa‘: ‘hello‘})
  3. Counter:计数器

    # Counter:计数器
    c = collections.Counter(‘abcdcadaadcag‘)
    print(c)                    # Counter({‘a‘: 5, ‘c‘: 3, ‘d‘: 3, ‘b‘: 1, ‘g‘: 1})
    print(c.most_common(3))     # [(‘a‘, 5), (‘c‘, 3), (‘d‘, 3)]

02 模块总结

  1. 自定义模块
  2. random
  3. time
  4. datetime
  5. os
  6. sys
  7. json
  8. pickle
  9. hashlib
  10. collections