Fork me on GitHub

学习python--023 Counter()函数

Counter函数旨在为我们统计列表中元素的数量并排序,非常适合词袋模型使用。

from collections import Counter
b = [1, 2, 3, 4, 1, 2, 1, 1, 4, 'a', 'a']
c = Counter(b)
>>> Counter({1: 4, 2: 2, 3: 1, 4: 2, 'a': 2})

Counter().most_common()方法:

通过给most_common()传参,Counter输出前。。行的元素。上代码。

c = Counter(b).most_common(2)
>>> c
[(1, 4), (2, 2)]

如上所示,Counter(b).most_common(2)输出了前2个最多类型的元素。




posted @ 2021-11-01 20:25  走位,走位  阅读(164)  评论(0编辑  收藏  举报