zoukankan      html  css  js  c++  java
  • Python容器数据类型——collections

    #!/usr/bin/python
    #coding=utf-8
    #http://docs.python.org/library/collections.html
    
    #count对象 Only 2.7
    from collections import Counter
    #统计字母出现的次数
    Counter('hello world')  
    Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
    
     #小于等于0的会被忽略
    c = Counter(a=4, b=2, c=0, d=-2)
    list(c.elements())
    #取前三个最多的字母
    Counter('hello world').most_common(3) 
    
    #
    from collections import deque
    d = deque('abc')
    d.append('d')
    d.pop() #后入先出
    d.popleft() #先入先出
    
    #返回最后n行文本
    deque(open(filename), n)
    
    #defaultdict
    from collections import defaultdict
    #使用list初始化一个dict
    d = defaultdict(list)
    d["yellow"].append(1)
    d["red"].append(2)
    d["yellow"].append(3)
    
    print d.items() #[('red', [2]), ('yellow', [1, 3])]
    #用int初始华一个dict
    d = defaultdict(int)
    d["yellow"] += 1
    d["red"] += 2
    d["yellow"] += 3
    print d.items() #[('red', 2), ('yellow', 4)]
  • 相关阅读:
    常用工具类
    手机端加载中
    jeecg的各种坑
    资源
    idea 破解后无法启动,我的配置文件搞错了
    eclipse xml 报某某.xsd找不到
    linux上部署svn服务器
    苹果手机微信浏览器无法通过post提交form数据
    %%%
    AtCoder arc060_d
  • 原文地址:https://www.cnblogs.com/goodspeed/p/python_collections.html
Copyright © 2011-2022 走看看