collections 模块之Counter

 Counter字典的子类,用于统计哈希对象

from collections import Counter

users = ["body1","body11","body13","body14","body11","body12","body13","body11"]

user_counter = Counter(users)

print (user_counter)    

#打印结果:
Counter({'body11': 3, 'body13': 2, 'body1': 1, 'body14': 1, 'body12': 1})
user1_counter
= Counter("abcdABCDAAccDd")    #统计字符串 print (user1_counter)
#打印结果:
Counter({'c': 3, 'A': 3, 'd': 2, 'D': 2, 'a': 1, 'b': 1, 'B': 1, 'C': 1})
user1_counter.update(user_counter)    #更新合并统计(将user_counter和user1_counter的数据合并统计)
print (user1_counter)
#打印结果:
Counter({'c': 3, 'A': 3, 'body11': 3, 'd': 2, 'D': 2, 'body13': 2, 'a': 1, 'b': 1, 'B': 1, 'C': 1, 'body1': 1, 'body14': 1, 'body12': 1})

user1_counter.update('1234')       #合并统计(将user1_counter的数据加入1234后统计)
print (user1_counter)

打印结果:
Counter({'c': 3, 'A': 3, 'body11': 3, 'd': 2, 'D': 2, 'body13': 2, 'a': 1, 'b': 1, 'B': 1, 'C': 1, 'body1': 1, 'body14': 1, 'body12': 1, '1': 1, '2': 1, '3': 1, '4': 1})
#统计出出现次数最多的前n个元素,示例打印前两个
print(user_counter.most_common(2))

#打印结果:
[('body11', 3), ('body13', 2)]

 

键的删除

>>> from collections import Counter
>>> c = Counter("abcdcba")
>>> c
Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
>>> del c["a"]
>>> c
Counter({'b': 2, 'c': 2, 'd': 1})
>>>

 

算术和集合操作

+、-、&、| 操作也可以用于Counter。其中&和|操作分别返回两个Counter对象各元素的最小值和最大值。需要注意的是,得到的Counter对象将删除小于1的元素。

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d  # c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d  # subtract(只保留正数计数的元素)
Counter({'a': 2})
>>> c & d  # 交集:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d  # 并集:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

 

其它操作

sum(c.values())  # 所有计数的总数
c.clear()  # 重置Counter对象,注意不是删除
list(c)  # 将c中的键转为列表
set(c)  # 将c中的键转为set
dict(c)  # 将c中的键值对转为字典
c.items()  # 转为(elem, cnt)格式的列表
Counter(dict(list_of_pairs))  # 从(elem, cnt)格式的列表转换为Counter类对象
c.most_common()[:-n:-1]  # 取出计数最少的n-1个元素
c += Counter()  # 移除0和负值

 

posted @ 2018-02-05 16:49  FRESHMANS  阅读(326)  评论(0编辑  收藏  举报