1.12 找出序列中出現(xiàn)次數(shù)最多的元素
- 可以使用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底層是用字典咪橙,記錄元素和它出現(xiàn)次數(shù)的一個映射
>>> 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})
- Counter也可以做數(shù)學(xué)加減運(yùn)算
>>> 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})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者