1.12 找出序列中出现次数最多的元素
- 可以使用collections Counter的most_common方法
>>> from collections import Counter
>>> word = ['look','look','hello','hello','hello']
>>> word_count = Counter(word)
>>> top = word_count.most_common(3)
>>> print(top)
[('hello', 3), ('look', 2)]
>>>
- Counter底层是用字典,记录元素和它出现次数的一个映射
>>> word_count
Counter({'hello': 3, 'look': 2})
>>> word_count["look"]
2
>>>
>>> more_word =["hello","tree"]
>>> for w in more_word:
... word_count[w]+=1
...
>>> word_count
Counter({'hello': 4, 'look': 2, 'tree': 1})
>>>
>>> word_count.update(more_word)
>>> word_count
Counter({'hello': 5, 'look': 2, 'tree': 2})
>>> a = Counter(word)
>>> b = Counter(more_word)
>>> a
Counter({'hello': 3, 'look': 2})
>>> b
Counter({'hello': 1, 'tree': 1})
>>> c =a+b
>>> c
Counter({'hello': 4, 'look': 2, 'tree': 1})
>>> d = a-b
>>> d
Counter({'look': 2, 'hello': 2})