collections
- Counter
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
# 将数据列表传入函数,
count_dic = Counter(words)
# print(count_dic,) 得到一个类字典类型,以列表中的可hash值为键,出现的次数为值
# Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})
# print(type(count_dic))
# <class 'collections.Counter'>
# print(count_dic.most_common())
# most_common方法中需要一个参数指定n条数据,不传入参数默认是将counter类型的字典转换为一个个元组,包含在一个列表中
# [('eyes', 8), ('the', 5), ('look', 4), ('into', 3), ('my', 3), ('around', 2), ('not', 1), ("don't", 1), ("you're", 1), ('under', 1)]
# print(count_dic.most_common(1))
# 指定1就只返回出现次数最多的那条数据
# [('eyes', 8)]
# 可以像字典一样直接指定键来取值,
# print(count_dic['eyes'])
# 8
# 也可以再指定一个列表做递增操作
# print(count_dic.most_common(3))
# [('eyes', 8), ('the', 5), ('look', 4)]
# add_tmp = ['eyes','the','look']
# count_dic.update(add_tmp)
# print(count_dic.most_common(3))
# [('eyes', 9), ('the', 6), ('look', 5)]
# 两个counter对象之间可以进行加减操作
A = ['eyes','the','look','eyes','the','look']
a = Counter(A)
print(a)
# Counter({'eyes': 2, 'the': 2, 'look': 2})
B = ['eyes','the','look']
b = Counter(B)
print(b)
# Counter({'eyes': 1, 'the': 1, 'look': 1})
c = a + b
print(c)
# Counter({'eyes': 3, 'the': 3, 'look': 3})