zoukankan      html  css  js  c++  java
  • 简述模块-collections

    collections模块主要封装了一些关于集合类的相关操作。

    1. Counter 是一个计数器,主要用来计数。

    from collections import Counter
    
    s = "汤汤今晚的晚饭有饺子汤"
    print(Counter(s))
    
    # Counter({'汤': 3, '晚': 2, '今': 1, '的': 1, '饭': 1, '有': 1, '饺': 1, '子': 1})
    from collections import Counter
    
    s = "汤汤今晚的晚饭有饺子汤"
    c = Counter(s)
    print(c.get(""))
    
    # 3


    2. defaultdict 默认值字典

    defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值:

    from collections import defaultdict
    
    dd = defaultdict(list)
    print(dd["牛肉汤"])
    
    # []


    3. OrderedDict 排序字典

    OrderedDict是按照输入顺序执行:

    from collections import OrderedDict
    
    dic = OrderedDict()
    dic["b"] = "牛肉汤"
    dic["a"] = "羊肉汤"
    print(dic)
    
    # OrderedDict([('b', '牛肉汤'), ('a', '羊肉汤')])
  • 相关阅读:
    SyntaxError: Non-ASCII character 'xe7' in file解决方法
    python实现微信打飞机游戏
    ubuntu 系统出错一览
    MVC的特点
    架构
    策略模式
    bin
    使用XSLT实现Word下载
    <a>标签的href属性
    call-template和apply-templates
  • 原文地址:https://www.cnblogs.com/wangzhilong/p/10197791.html
Copyright © 2011-2022 走看看