• 【python】collections的使用


    老师布置了一个课后作业。

    统计文本中字母出现的次数并找到最大的那一个

    首先是读取文本吧。和c里的也差不多,打开,关闭,读取。

     1 path = 'YourPath' 2 f = open(path) 3 f.close() 

    然后就用到了这个黑科技。collections里的Counter。计数功能很强大。

    代码:

     1 from collections import Counter
     2 
     3 path = 'YourPath'
     4 f = open(path)
     5 lines = f.readlines()
     6 strs = []
     7 for line in lines:
     8 
     9     for i in line:
    10         if i >= 'a' and i <= 'z':
    11             strs.append(i)
    12         if i >= 'A' and i <= 'Z':
    13             strs.append(i)
    14 #print(Counter(strs))
    15 print(Counter(strs).most_common(1))
    16 f.close()

    导入模式如上图。Counter可以对list里的元素计数。并且有专门的方法调用返回最大值,并且默认返回最大值的值以最大值那个数。

    常用操作:

     1 # 所有计数的总数
     2 sum(c.values())
     3 # 重置Counter对象,注意不是删除
     4 c.clear()
     5 # 将c中的键转为列表
     6 list(c)
     7 # 将c中的键转为set
     8 set(c)
     9 # 将c中的键值对转为字典
    10 dict(c)  
    11 #取出计数最多的n个元素
    12 c.most_common(n)
    13 # 取出计数最少的n-1个元素
    14 c.most_common()[:-n:-1]
    15 # 移除0和负值
    16 c += Counter()  

    有任何好的见解或者我有任何错误都请评论鸭qwq

  • 相关阅读:
    poj 2262
    poj 1050
    poj 1730
    poj 1061
    【设计模式】简单工厂模式学习
    【待学】
    [设计模式]策略模式和单一职责
    Windows live writer 误删 草稿 恢复
    [Linq]Linq To Sql (2)
    MVC 学习日志1(上)
  • 原文地址:https://www.cnblogs.com/Asumi/p/9620578.html
Copyright © 2020-2023  润新知