# python中统计列表中各个元素个数/次数的模块

import collections.Counter

###### Counter 常用法举例
• 直接显示各个元素频次
• 可以使用most_common显示最多的n个元素
• 可以使用数组下标的访问方式像字典一样获取某个元素的出现次数
import collections

a='1234234567'
b=collections.Counter(a)

print(b)
print(b.most_common)
print(b.most_common(2))
print("number of '2': {}".format(b['2']))


Counter({'2': 2, '3': 2, '4': 2, '1': 1, '5': 1, '6': 1, '7': 1})
<bound method Counter.most_common of Counter({'2': 2, '3': 2, '4': 2, '1': 1, '5': 1, '6': 1, '7': 1})>
[('2', 2), ('3', 2)]
number of '2': 2

• Counter不仅可以统计字符串内元素情况，还可以统计列表内元素情况，只要列表对象是hashable的。

• 得到Counter计数器对象后，还可以在上面做加减的增量更新。使用subtract成员函数，从计数结果中减去一些元素；通过update函数可以增加元素统计。

b.subtract('abc')
print(b)
b.update('opq')
print(b)

Counter({'2': 2, '3': 2, '4': 2, '1': 1, '5': 1, '6': 1, '7': 1, 'a': -1, 'b': -1, 'c': -1})
Counter({'2': 2, '3': 2, '4': 2, '1': 1, '5': 1, '6': 1, '7': 1, 'o': 1, 'p': 1, 'q': 1, 'a': -1, 'b': -1, 'c': -1})

###### 什么是hashable？

hashable ≈ imutable 可哈希 ≈ 不可变

list、set和dictionary 都是可改变的，比如可以通过list.append()，set.remove()，dict[‘key’] = value对其进行修改，所以它们都是不可哈希的；

An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() or cmp() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

————————————————

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客