python -- Counter 类

python -- Counter 类


enter description here

我明白你会来,所以我等


参考

官方文档


class collections.Counter([iterable-or-mapping])

Counter 集成于 dict 类,因此也可以使用字典的方法,此类返回一个以元素为 key 、元素个数为 value 的 Counter 对象集合

>>> from collections import Counter
>>> s = "hello pinsily"
>>> d = Counter(s)
>>> d
Counter({'l': 3, 'i': 2, 'h': 1, 'e': 1, 'o': 1, ' ': 1, 'p': 1, 'n': 1, 's': 1, 'y': 1})

elements()

返回一个迭代器

>>> d.elements()
<itertools.chain object at 0x0000019AC812BBA8>

# 可以进行打印和排序
>>> for i in d.elements():
...     	print(i)
...


most_common(n)

返回数量最多的前 n 个元素

>>> d.most_common(3)
[('l', 3), ('i', 2), ('h', 1)]

subtract([iterable-or-mapping])

相当于减法,调用这个方法的 Counter 会被覆盖掉

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
>>> d
Counter({'d': 4, 'c': 3, 'b': 2, 'a': 1})

总结

当需要对 list 中的大量数据进行计数时,可以直接使用 Counter ,而不用新建字典来计数


原文地址:https://www.cnblogs.com/pinsily/p/7906107.html