Python内建的一个集合模块:collections:搭建数据分析体系80篇

collections集合模块中有许多有用的集合类。

比如:namedtuple,deque,defaultdict,OrderedDict,Counter。

Python内建的一个集合模块:collections:搭建数据分析体系80篇

这里看一下Counter集合类。这个集合类是用于计数的。

Counter是一个简单的计数器。

Counter也是dict(字典)的一个子类。

查看字典的元素可以用[],可用items取字典的所有元素进行遍历。

word_count=Counter() #集合类。创建了类对象

for item in word_count.items():#遍历字典的所有元素items

在统计词频的程序开发中,可以用于统计字符出现的个数。

from collections import Counter

>>> c = Counter()

>>> for ch in 'programming':

... c[ch] = c[ch] + 1

...

>>> c

Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})


分享到:


相關文章: