1. 程式人生 > >collections 模塊之Counter

collections 模塊之Counter

cdd clas cda log 字符串 from most users color

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