zoukankan      html  css  js  c++  java
  • Python中对序列数据的汇总(collections模块)

    目录

    Counter

    most_common 


    对于序列如字符串str、列表list和tuple可以统计里面数据出现的次数。我们使用的是 collections 模块。

    collections模块的常用方法有:

    • 计数器(Counter)
    • 双向队列(deque)
    • 默认字典(defaultdict)
    • 有序字典(OrderedDict)
    • 可命名元组(namedtuple)

    使用以上类型时需要导入模块 from collections import *

    Counter

    Counter()方法对传入的序列中出现的数据进行汇总,返回一个<class 'collections.Counter'>的对象

    from collections import Counter
    a="aabcac"
    b=['a','a','b','c','a','c']
    c=('a','a','b','c','a','c')
    print(Counter(a),type(Counter(a)))
    print(Counter(b))
    print(Counter(c))
    #######################################
    Counter({'a': 3, 'c': 2, 'b': 1}) <class 'collections.Counter'>
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})

    most_common 

    most_common方法对Counter()汇总的数据进行从高到低的排序,返回前 n 个元素的字典,返回的是列表型的数据

    from collections import Counter
    a="aabcac"
    b=['a','a','b','c','a','c']
    c=('a','a','b','c','a','c')
    print(Counter(a))
    print(Counter(b))
    print(Counter(c))
    
    print(Counter(a).most_common(3),type(Counter(a).most_common(3)))
    print(Counter(b).most_common(2))
    print(Counter(c).most_common(1))
    ##############################################
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})
    [('a', 3), ('c', 2), ('b', 1)] <class 'list'>
    [('a', 3), ('c', 2)]
    [('a', 3)]
  • 相关阅读:
    Docker入门(windows版),利用Docker创建一个Hello World的web项目
    SpringBoot集成JWT实现token验证
    Jedis的基本操作
    Java动态代理详解
    SpringBoot利用自定义注解实现通用的JWT校验方案
    递归——汉诺塔问题(python实现)
    Datatable删除行的Delete和Remove方法的区别
    C# DEV使用心得
    总结
    安装插件时
  • 原文地址:https://www.cnblogs.com/csnd/p/11807836.html
Copyright © 2011-2022 走看看