博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Counter class
阅读量:4577 次
发布时间:2019-06-08

本文共 1675 字,大约阅读时间需要 5 分钟。

Counter class

# class collections.Counter([iterable-or-mapping])# A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.>>> # Tally occurrences of words in a list>>> cnt = Counter()>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:...     cnt[word] += 1>>> cntCounter({'blue': 3, 'red': 2, 'green': 1})>>> # Find the ten most common words in Hamlet>>> import re>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())>>> Counter(words).most_common(10)[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] sum(c.values())                 # total of all countsc.clear()                       # reset all countslist(c)                         # list unique elementsset(c)                          # convert to a setdict(c)                         # convert to a regular dictionaryc.items()                       # convert to a list of (elem, cnt) pairsCounter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairsc.most_common()[:-n-1:-1]       # n least common elementsc += Counter()                  # remove zero and negative counts# most_common([n])# Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.

转载于:https://www.cnblogs.com/songdanzju/p/7441683.html

你可能感兴趣的文章
MapRedece(单表关联)
查看>>
蒲公英App开发之检测新版本
查看>>
【安卓基础】倒计时按钮封装(验证码倒计时按钮)
查看>>
configparser模块
查看>>
SelectQueryBuilder的用法
查看>>
android的用户定位(一)
查看>>
creat-react-app搭建的项目中按需引入antd以及配置Less和如何修改antd的主题色
查看>>
IIS安装
查看>>
html块级元素和行级元素的区别和使用
查看>>
for循环嵌套
查看>>
寒冬夜行人
查看>>
poj1151 Atlantis
查看>>
HTML页面之间的参数传递
查看>>
java面试题集锦
查看>>
scikit-learn:4.2.3. Text feature extraction
查看>>
Spring Security构建Rest服务-0800-Spring Security图片验证码
查看>>
AE待整理
查看>>
java8中规范的四大函数式接口
查看>>
宝塔apache配置
查看>>
shell脚本中使用nohup执行命令不生效
查看>>