例子

普通实现

  1. #统计词频
  2. colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
  3. result = {}
  4. for color in colors:
  5. if result.get(color)==None:
  6. result[color]=1
  7. else:
  8. result[color]+=1
  9. print (result)
  10. #{'red': 2, 'blue': 3, 'green': 1}

用counter实现

  1. from collections import Counter
  2. colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
  3. c = Counter(colors)
  4. print (dict(c))

Counter操作

可以创建一个空的Counter:

  1. cnt = Counter()

之后在空的Counter上进行一些操作。
也可以创建的时候传进去一个迭代器(数组,字符串,字典等):

  1. c = Counter('gallahad') # 传进字符串
  2. c = Counter({'red': 4, 'blue': 2}) # 传进字典
  3. c = Counter(cats=4, dogs=8) # 传进元组

判断是否包含某元素,可以转化为dict然后通过dict判断,Counter也带有函数可以判断:

  1. c = Counter(['eggs', 'ham'])
  2. c['bacon'] # 不存在就返回0
  3. #0

https://blog.csdn.net/qwe1257/article/details/83272340