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)]