collections 模块之Counter

Posted FRESHMANS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了collections 模块之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)]

 

以上是关于collections 模块之Counter的主要内容,如果未能解决你的问题,请参考以下文章

collections模块—— Counter

python模块之collections random

collections模块—— Counter

python之collections模块

python--模块之collection

找不到模块:无法解析'C: Users test counter-app src'中的'bootstrap / dist / css / bootstrap.cs(代码片