python3中遇到的实用函数

2018-12-08  本文已影响0人  脏脏包盛

collections包

Counter

Counter是dict子类,用于计算哈希对象。它是一个无序集合,其元素存储为字典键, 其计数存储为字典值。计数允许为任何整数值,包括0和负计算值。
初始化
可以初始化Countered从interable, 或者另一个mapping(可以为Counter类的对象)
注:interable应该就是“序列”吧,字符串、列表、元组等

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

结果类似如下,key:value形势,value就是统计的出现个数
Out:
Counter({'a': 3, 'd': 1, 'g': 1, 'h': 1, 'l': 2})
Counter({'red': 4, 'blue': 8})
Counter({'cats': 4, 'dogs': 8})

如果没有计数的项则返回0,而不是KeyError

 c = Counter(['eggs', 'ham'])
c['abcd']

Out:0
删除和加入某一项

c['sausage'] = 0        # 添加
del c['sausage']        #删除该key-value项

方法
支持除了字典方法以外的三种方法

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
>>> Counter('abracadabra').most_common(3)  # doctest: +SKIP
[('a', 5), ('r', 2), ('b', 2)]
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4,e = 3)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6, 'e': -3})
上一篇 下一篇

猜你喜欢

热点阅读