标签:== entry abr mon res amp 字典 函数 常见
Counter中文意思是计数器,也就是我们常用于统计的一种数据类型,在使用Counter之后可以让我们的代码更加简单易读。
我们先看一个简单的例子:
#统计词频
colors = [‘red‘, ‘blue‘, ‘red‘, ‘green‘, ‘blue‘, ‘blue‘]
result = {}
for color in colors:
if result.get(color)==None:
result[color]=1
else:
result[color]+=1
print (result)
#{‘red‘: 2, ‘blue‘: 3, ‘green‘: 1}
1.下面我们看用Counter怎么实现:
from collections import Counter
colors = [‘red‘, ‘blue‘, ‘red‘, ‘green‘, ‘blue‘, ‘blue‘]
c = Counter(colors)
print(c)
#Counter({‘blue‘: 3, ‘green‘: 1, ‘red‘: 2})
print (dict(c))
#{‘red‘: 2, ‘blue‘: 3, ‘green‘: 1}
2.创建Counter的时候传进去一个迭代器(数组,字符串,字典等):
c = Counter(‘gallahad‘) # 传进字符串
print(c)
#Counter({‘a‘: 3, ‘d‘: 1, ‘g‘: 1, ‘h‘: 1, ‘l‘: 2})
c = Counter({‘red‘: 4, ‘blue‘: 2}) # 传进字典
print(c)
#Counter({‘blue‘: 2, ‘red‘: 4})
c = Counter(cats=4, dogs=8) # 传进元组
print(c)
#Counter({‘cats‘: 4, ‘dogs‘: 8})
3.判断是否包含某元素,可以转化为dict然后通过dict判断,Counter也带有函数可以判断:
c = Counter([‘eggs‘, ‘ham‘])
print(c)
#Counter({‘eggs‘: 1, ‘ham‘: 1})
c[‘bacon‘] # 不存在就返回0
#0
4.删除元素:
c[‘sausage‘] = 0 # counter entry with a zero count
del c[‘sausage‘]
5.获得所有元素:
c = Counter(a=4, b=2, c=0, d=-2)
print(c)
#Counter({‘a‘: 4, ‘b‘: 2, ‘c‘: 0, ‘d‘: -2})
list(c.elements())
#[‘a‘, ‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘b‘]
6.查看最常见出现的k个元素:
Counter(‘abracadabra‘).most_common(3)
#[(‘a‘, 5), (‘r‘, 2), (‘b‘, 2)]
7.Counter更新:
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # 相加
#Counter({‘a‘: 4, ‘b‘: 3})
c - d # 相减,如果小于等于0,删去
#Counter({‘a‘: 2})
c & d # 求最小
#Counter({‘a‘: 1, ‘b‘: 1})
c | d # 求最大
#Counter({‘a‘: 3, ‘b‘: 2})
原文链接:https://blog.csdn.net/qwe1257/article/details/83272340
标签:== entry abr mon res amp 字典 函数 常见
原文地址:https://www.cnblogs.com/USTC-ZCC/p/12884226.html