问题: 怎样找出一个序列中出现次数最多的元素呢?

answer: collections.Counter 类就是专门为这类问题而设计的,它甚至有一个有用的most_common() 方法直接给了你答案

 

eg:

  words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes','look', 'into', 'my']

  words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes','look', 'into', 'my','you']
  >>>from collections import Counter

1.出现频率最高的3 个单词
  >>>word_counts = Counter(words)

  >>>top_three = word_counts.most_common(3)
  >>>print(top_three)
  [('look', 3), ('into', 3), ('my', 3)]

2.某一个单词出现的次数

  >>> word_counts['eyes']
  2

3.Counter跟数学运算相结合

  >>>a=Counter(words)

  >>>b=Counter(wordss)

  >>>c=a+b

  >>>d=a-b

  >>>e=b-a

  >>>e

  Counter({'you':1}) 

Counter对象在几乎所有需要制表或者计数的场合是非常有用的工具。解决这类问题时应优先选择它,而不是手动的利用字典去实现。