collection 中 Counter的使用

collection.Counter 的使用

“””
https://docs.python.org/3.6/library/collections.html#collections.Counter
Counter 是 dict 子类
A counter tool is provided to support convenient and rapid tallies.
提供计数器工具以支持方便快捷的计数。
“”“

来看一个小例子

from collections import Counter


cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'red','blue','red','blue', 'green', 'red','blue','black','green', 'red','blue','black']:
    cnt[word] += 1
print(cnt)

# Counter({'red': 6, 'blue': 5, 'green': 3, 'black': 2})

是不是非常方便.

让我们来看一下, Counter 类的用法
构造一个counter 用以下4种方法

c = Counter()
c1= Counter('gallahadsfsjijfwojfewo')  
c1
Counter({'a': 3, 'f': 3, 'j': 3, 'l': 2, 's': 2, 'w': 2, 'o': 2, 'g': 1, 'h': 1, 'd': 1, 'i': 1, 'e': 1})

c1['a']
3
c2 = Counter({'red': 4, 'blue': 2}) 
c3 = Counter(cats=4, dogs=8)   

# 注意这里不会抛出异常,会直接返回0 , 当访问不存在的key 的时候,直接返回0 
c3['aaa']  返回0 ,不会抛出异常 .

如果想要删除 某个key , 可以用 del, 或者 pop 来删除.

c4
Counter({'eggs': 10, 'ham': 1})
c4['eggs'] =0
c4
Counter({'ham': 1, 'eggs': 0})

把counter 设置成0 , 不会移除,这个字符. 要移除可以使用 del c4['eggs']
# 或者 像字典方式一样 
c4.pop('eggs')

查看元素 可以用 elements

c = Counter(a=4, b=2, c=0, d=-2)
c.elements()
<itertools.chain object at 0x10b6dfa90>

list(c.elements())
sorted(c.elements())

<itertools.chain object at 0x108de5320>
['a', 'a', 'a', 'a', 'b', 'b']

还有一个方法 我经常喜欢用 most_common([n])
most_common([n])

### most_common  
most_common([n])
就是返回是一个列表, 列表元素是一个元祖, 分别是(元素,个数), n 指定前几个,不指定的话,就是返回全部的计数结果,按从高到底排序

# n 指定返回 top n , 不指定全部返回. 返回一个列表, 列表中的元素 是一个元祖, (元素, 个数) 这样的一个形式
# [(元素,个数),(元素,个数),(元素,个数),(元素,个数),(),()]
"""
eturn a list of the n most common elements and their counts from the most common to the least. 
If n is omitted or None, most_common() returns all elements in the counter. 
Elements with equal counts are ordered arbitrarily:
"""

# 来看一个例子
c1= Counter('gallahasjoadsaosjfoisdsfsjijfwojfewo')  
c1
Counter({'s': 6, 'a': 5, 'j': 5, 'o': 5, 'f': 4, 'l': 2, 'd': 2, 'i': 2, 'w': 2, 'g': 1, 'h': 1, 'e': 1})
c1.most_common(2)
[('s', 6), ('a', 5)]

还有一个方法 subtract

就是相同的key ,可以直接相减 
# 函数 不返回值, 直接在原来的counter 里面减掉,所有的值都会被保留, 包括负数
# 该函数 会保留所有的值 , 如果存在不存在的key 相减, 默认不存在的key 的值为0 ,进行相减
"""
Elements are subtracted from an iterable or from another mapping (or counter).
 Like dict.update() but subtracts counts instead of replacing them.
 Both inputs and outputs may be zero or negative.
"""

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})

对于不存在的key ,相减的时候,默认key的值为0 ,进行相减,保留负数
看下面的例子

#
# for example 
c = Counter(a=4, b=2, c=0, d=-2,f=10)
d = Counter(a=1, b=2, c=3, d=4,g=66)

c.subtract(d)
c
Counter({'f': 10, 'a': 3, 'b': 0, 'c': -3, 'd': -6, 'g': -66})

# f 字符在 d 中没有,然后结果就是c中的值. 

重置 counter 可以用 clear

from collections import Counter

c = Counter(a=4, b=2, c=0, d=-2,f=10)
c
Counter({'f': 10, 'a': 4, 'b': 2, 'c': 0, 'd': -2})
c.clear()
c
Counter()

将counter 转成 (key,count) 的 list

# convert to a list of (elem, cnt) pairs
c = Counter(a=4, b=2, c=0, d=12,f=10)
c.items()
dict_items([('a', 4), ('b', 2), ('c', 0), ('d', 12), ('f', 10)])
for elem ,cnt in  c.items():
    print(elem,cnt)

获取所有的统计次数 values()

c
Counter({'d': 12, 'f': 10, 'a': 4, 'b': 2, 'c': 0})
c.values()
dict_values([4, 2, 0, 12, 10])
sum(c.values())
28

列出所有的key 可以直接用list(counter)

c=Counter({'d': 12, 'f': 10, 'a': 4, 'b': 2, 'c': 0})
list(c)
['d', 'f', 'a', 'b', 'c']
b =sorted(list(c))
b
['a', 'b', 'c', 'd', 'f']

运算符 + - | & 在counter 中的使用

+ 会把相同的key 相加, 
- 会把相同的key 相减, 但是只保留正数,对于值为0,或者负数的key ,会被删除. 
&  intersection:  min(c[x], d[x]) ,相同的key 求最小的值,也是只保留正数的key , 负数的key 将会被删除 

|  union:  max(c[x], d[x])   这个是取最大值 ,也是只保留正数的key
c = Counter(a=10,b=5,c=6)
d = Counter(a=3,b=8,c =6)
c -d
Counter({'a': 7})
c +d
Counter({'a': 13, 'b': 13})

来看下 & |

c
Counter({'a': 10, 'c': 6, 'b': 5})
d
Counter({'b': 8, 'a': 3, 'c': -5, 'd': -10})
c& d
Counter({'b': 5, 'a': 3})

# 可以看到c 这个key 被删除了, 因为key 的值 小于等于0 

c = Counter(a=10,b=5,c=-6)
d = Counter(a=3,b=8,c =-1)
c | d
Counter({'a': 10, 'b': 8})

# 可以看到c 这个key 被删除了, 因为key 的值 小于等于0 

举个例子, 这个例子来自LeetCode 习题

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且数组中的众数永远存在。

向下取整的运算称为Floor,用数学符号⌊⌋表示;向上取整的运算称为Ceiling,用数学符号⌈⌉表示。例如:
⌊59/60⌋=059/60⌉=1
⌊-59/60⌋=-1
⌈-59/60⌉=0
import collections
# 大神的代码 
class Solution:
    """
    48ms
    """
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        couters=collections.Counter(nums)
        return max(couters.keys(),key=couters.get)

代码首先 用counter ,将所有的数组,计数, 之后调用max 系统函数,把 counter的keys 作为 目标,key 定义成 counter 的get 方法,这样就找到出现次数最多的那个数了.

总结

本文主要讲了一些 counter 中基本的用法, 也算是学习笔记, 这个类用来计数非常方便,效率方面还是挺高的.

         分享快乐,留住感动. 2018-04-22 10:40:55  --frank

猜你喜欢

转载自blog.csdn.net/u010339879/article/details/80036755