Counter

Posted on 2018-03-10 02:12  gamehq  阅读(247)  评论(0)    收藏  举报

Counter

  • 类似于数学中的多重集
  • import collections
  • update() 更新内容,注意是做“加法”,不是“替换”
  • 访问内容[key]
  • 注意和dict的区别:如果Counter中不存在key值,返回0;而dict会报错
  • elements()方法,返回所有元素
  • most_common()方法,返回n前多的数据

  

Counter

 

 

  • 初始化
1 import collections
2 
3 c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
4 c2 = collections.Counter({'a':2, 'b':3, 'c':1})
5 c3 = collections.Counter(a=2, b=3, c=1)
6 
7 print(c1)
8 print(c2)
9 print(c3)
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

  • 更新内容
1 # 注意这里是做“加法”,不是“替换”
2 c1.update({'a': 4, 'c': -2, 'd': 4})
3 print(c1)
Counter({'a': 6, 'd': 4, 'b': 3, 'c': -1})

  • 访问内容
1 print('a=', c1['a'])
2 print('b=', c1['b'])
3 # 对比和dict的区别
4 print('e=', c1['e'])
a= 6
b= 3
e= 0